4effa4d7c54dfabf78bbd31a15da56c897088b27
[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');
41 // Marker filter for grading page.
42 define('ASSIGN_MARKER_FILTER_NO_MARKER', -1);
44 // Reopen attempt methods.
45 define('ASSIGN_ATTEMPT_REOPEN_METHOD_NONE', 'none');
46 define('ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL', 'manual');
47 define('ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS', 'untilpass');
49 // Special value means allow unlimited attempts.
50 define('ASSIGN_UNLIMITED_ATTEMPTS', -1);
52 // Marking workflow states.
53 define('ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED', 'notmarked');
54 define('ASSIGN_MARKING_WORKFLOW_STATE_INMARKING', 'inmarking');
55 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW', 'readyforreview');
56 define('ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW', 'inreview');
57 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE', 'readyforrelease');
58 define('ASSIGN_MARKING_WORKFLOW_STATE_RELEASED', 'released');
60 // Name of file area for intro attachments.
61 define('ASSIGN_INTROATTACHMENT_FILEAREA', 'introattachment');
63 require_once($CFG->libdir . '/accesslib.php');
64 require_once($CFG->libdir . '/formslib.php');
65 require_once($CFG->dirroot . '/repository/lib.php');
66 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
67 require_once($CFG->libdir . '/gradelib.php');
68 require_once($CFG->dirroot . '/grade/grading/lib.php');
69 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
70 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
71 require_once($CFG->dirroot . '/mod/assign/renderable.php');
72 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
73 require_once($CFG->libdir . '/eventslib.php');
74 require_once($CFG->libdir . '/portfolio/caller.php');
76 /**
77  * Standard base class for mod_assign (assignment types).
78  *
79  * @package   mod_assign
80  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
81  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
82  */
83 class assign {
85     /** @var stdClass the assignment record that contains the global settings for this assign instance */
86     private $instance;
88     /** @var stdClass the grade_item record for this assign instance's primary grade item. */
89     private $gradeitem;
91     /** @var context the context of the course module for this assign instance
92      *               (or just the course if we are creating a new one)
93      */
94     private $context;
96     /** @var stdClass the course this assign instance belongs to */
97     private $course;
99     /** @var stdClass the admin config for all assign instances  */
100     private $adminconfig;
102     /** @var assign_renderer the custom renderer for this module */
103     private $output;
105     /** @var cm_info the course module for this assign instance */
106     private $coursemodule;
108     /** @var array cache for things like the coursemodule name or the scale menu -
109      *             only lives for a single request.
110      */
111     private $cache;
113     /** @var array list of the installed submission plugins */
114     private $submissionplugins;
116     /** @var array list of the installed feedback plugins */
117     private $feedbackplugins;
119     /** @var string action to be used to return to this page
120      *              (without repeating any form submissions etc).
121      */
122     private $returnaction = 'view';
124     /** @var array params to be used to return to this page */
125     private $returnparams = array();
127     /** @var string modulename prevents excessive calls to get_string */
128     private static $modulename = null;
130     /** @var string modulenameplural prevents excessive calls to get_string */
131     private static $modulenameplural = null;
133     /** @var array of marking workflow states for the current user */
134     private $markingworkflowstates = null;
136     /** @var bool whether to exclude users with inactive enrolment */
137     private $showonlyactiveenrol = null;
139     /** @var array cached list of participants for this assignment. The cache key will be group, showactive and the context id */
140     private $participants = array();
142     /**
143      * Constructor for the base assign class.
144      *
145      * Note: For $coursemodule you can supply a stdclass if you like, but it
146      * will be more efficient to supply a cm_info object.
147      *
148      * @param mixed $coursemodulecontext context|null the course module context
149      *                                   (or the course context if the coursemodule has not been
150      *                                   created yet).
151      * @param mixed $coursemodule the current course module if it was already loaded,
152      *                            otherwise this class will load one from the context as required.
153      * @param mixed $course the current course  if it was already loaded,
154      *                      otherwise this class will load one from the context as required.
155      */
156     public function __construct($coursemodulecontext, $coursemodule, $course) {
157         $this->context = $coursemodulecontext;
158         $this->course = $course;
160         // Ensure that $this->coursemodule is a cm_info object (or null).
161         $this->coursemodule = cm_info::create($coursemodule);
163         // Temporary cache only lives for a single request - used to reduce db lookups.
164         $this->cache = array();
166         $this->submissionplugins = $this->load_plugins('assignsubmission');
167         $this->feedbackplugins = $this->load_plugins('assignfeedback');
168     }
170     /**
171      * Set the action and parameters that can be used to return to the current page.
172      *
173      * @param string $action The action for the current page
174      * @param array $params An array of name value pairs which form the parameters
175      *                      to return to the current page.
176      * @return void
177      */
178     public function register_return_link($action, $params) {
179         global $PAGE;
180         $params['action'] = $action;
181         $currenturl = $PAGE->url;
183         $currenturl->params($params);
184         $PAGE->set_url($currenturl);
185     }
187     /**
188      * Return an action that can be used to get back to the current page.
189      *
190      * @return string action
191      */
192     public function get_return_action() {
193         global $PAGE;
195         $params = $PAGE->url->params();
197         if (!empty($params['action'])) {
198             return $params['action'];
199         }
200         return '';
201     }
203     /**
204      * Based on the current assignment settings should we display the intro.
205      *
206      * @return bool showintro
207      */
208     public function show_intro() {
209         if ($this->get_instance()->alwaysshowdescription ||
210                 time() > $this->get_instance()->allowsubmissionsfromdate) {
211             return true;
212         }
213         return false;
214     }
216     /**
217      * Return a list of parameters that can be used to get back to the current page.
218      *
219      * @return array params
220      */
221     public function get_return_params() {
222         global $PAGE;
224         $params = $PAGE->url->params();
225         unset($params['id']);
226         unset($params['action']);
227         return $params;
228     }
230     /**
231      * Set the submitted form data.
232      *
233      * @param stdClass $data The form data (instance)
234      */
235     public function set_instance(stdClass $data) {
236         $this->instance = $data;
237     }
239     /**
240      * Set the context.
241      *
242      * @param context $context The new context
243      */
244     public function set_context(context $context) {
245         $this->context = $context;
246     }
248     /**
249      * Set the course data.
250      *
251      * @param stdClass $course The course data
252      */
253     public function set_course(stdClass $course) {
254         $this->course = $course;
255     }
257     /**
258      * Get list of feedback plugins installed.
259      *
260      * @return array
261      */
262     public function get_feedback_plugins() {
263         return $this->feedbackplugins;
264     }
266     /**
267      * Get list of submission plugins installed.
268      *
269      * @return array
270      */
271     public function get_submission_plugins() {
272         return $this->submissionplugins;
273     }
275     /**
276      * Is blind marking enabled and reveal identities not set yet?
277      *
278      * @return bool
279      */
280     public function is_blind_marking() {
281         return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
282     }
284     /**
285      * Does an assignment have submission(s) or grade(s) already?
286      *
287      * @return bool
288      */
289     public function has_submissions_or_grades() {
290         $allgrades = $this->count_grades();
291         $allsubmissions = $this->count_submissions();
292         if (($allgrades == 0) && ($allsubmissions == 0)) {
293             return false;
294         }
295         return true;
296     }
298     /**
299      * Get a specific submission plugin by its type.
300      *
301      * @param string $subtype assignsubmission | assignfeedback
302      * @param string $type
303      * @return mixed assign_plugin|null
304      */
305     public function get_plugin_by_type($subtype, $type) {
306         $shortsubtype = substr($subtype, strlen('assign'));
307         $name = $shortsubtype . 'plugins';
308         if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
309             return null;
310         }
311         $pluginlist = $this->$name;
312         foreach ($pluginlist as $plugin) {
313             if ($plugin->get_type() == $type) {
314                 return $plugin;
315             }
316         }
317         return null;
318     }
320     /**
321      * Get a feedback plugin by type.
322      *
323      * @param string $type - The type of plugin e.g comments
324      * @return mixed assign_feedback_plugin|null
325      */
326     public function get_feedback_plugin_by_type($type) {
327         return $this->get_plugin_by_type('assignfeedback', $type);
328     }
330     /**
331      * Get a submission plugin by type.
332      *
333      * @param string $type - The type of plugin e.g comments
334      * @return mixed assign_submission_plugin|null
335      */
336     public function get_submission_plugin_by_type($type) {
337         return $this->get_plugin_by_type('assignsubmission', $type);
338     }
340     /**
341      * Load the plugins from the sub folders under subtype.
342      *
343      * @param string $subtype - either submission or feedback
344      * @return array - The sorted list of plugins
345      */
346     protected function load_plugins($subtype) {
347         global $CFG;
348         $result = array();
350         $names = core_component::get_plugin_list($subtype);
352         foreach ($names as $name => $path) {
353             if (file_exists($path . '/locallib.php')) {
354                 require_once($path . '/locallib.php');
356                 $shortsubtype = substr($subtype, strlen('assign'));
357                 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
359                 $plugin = new $pluginclass($this, $name);
361                 if ($plugin instanceof assign_plugin) {
362                     $idx = $plugin->get_sort_order();
363                     while (array_key_exists($idx, $result)) {
364                         $idx +=1;
365                     }
366                     $result[$idx] = $plugin;
367                 }
368             }
369         }
370         ksort($result);
371         return $result;
372     }
374     /**
375      * Display the assignment, used by view.php
376      *
377      * The assignment is displayed differently depending on your role,
378      * the settings for the assignment and the status of the assignment.
379      *
380      * @param string $action The current action if any.
381      * @return string - The page output.
382      */
383     public function view($action='') {
385         $o = '';
386         $mform = null;
387         $notices = array();
388         $nextpageparams = array();
390         if (!empty($this->get_course_module()->id)) {
391             $nextpageparams['id'] = $this->get_course_module()->id;
392         }
394         // Handle form submissions first.
395         if ($action == 'savesubmission') {
396             $action = 'editsubmission';
397             if ($this->process_save_submission($mform, $notices)) {
398                 $action = 'redirect';
399                 $nextpageparams['action'] = 'view';
400             }
401         } else if ($action == 'editprevioussubmission') {
402             $action = 'editsubmission';
403             if ($this->process_copy_previous_attempt($notices)) {
404                 $action = 'redirect';
405                 $nextpageparams['action'] = 'editsubmission';
406             }
407         } else if ($action == 'lock') {
408             $this->process_lock_submission();
409             $action = 'redirect';
410             $nextpageparams['action'] = 'grading';
411         } else if ($action == 'addattempt') {
412             $this->process_add_attempt(required_param('userid', PARAM_INT));
413             $action = 'redirect';
414             $nextpageparams['action'] = 'grading';
415         } else if ($action == 'reverttodraft') {
416             $this->process_revert_to_draft();
417             $action = 'redirect';
418             $nextpageparams['action'] = 'grading';
419         } else if ($action == 'unlock') {
420             $this->process_unlock_submission();
421             $action = 'redirect';
422             $nextpageparams['action'] = 'grading';
423         } else if ($action == 'setbatchmarkingworkflowstate') {
424             $this->process_set_batch_marking_workflow_state();
425             $action = 'redirect';
426             $nextpageparams['action'] = 'grading';
427         } else if ($action == 'setbatchmarkingallocation') {
428             $this->process_set_batch_marking_allocation();
429             $action = 'redirect';
430             $nextpageparams['action'] = 'grading';
431         } else if ($action == 'confirmsubmit') {
432             $action = 'submit';
433             if ($this->process_submit_for_grading($mform, $notices)) {
434                 $action = 'redirect';
435                 $nextpageparams['action'] = 'view';
436             } else if ($notices) {
437                 $action = 'viewsubmitforgradingerror';
438             }
439         } else if ($action == 'submitotherforgrading') {
440             if ($this->process_submit_other_for_grading($mform, $notices)) {
441                 $action = 'redirect';
442                 $nextpageparams['action'] = 'grading';
443             } else {
444                 $action = 'viewsubmitforgradingerror';
445             }
446         } else if ($action == 'gradingbatchoperation') {
447             $action = $this->process_grading_batch_operation($mform);
448             if ($action == 'grading') {
449                 $action = 'redirect';
450                 $nextpageparams['action'] = 'grading';
451             }
452         } else if ($action == 'submitgrade') {
453             if (optional_param('saveandshownext', null, PARAM_RAW)) {
454                 // Save and show next.
455                 $action = 'grade';
456                 if ($this->process_save_grade($mform)) {
457                     $action = 'redirect';
458                     $nextpageparams['action'] = 'grade';
459                     $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
460                     $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
461                 }
462             } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
463                 $action = 'redirect';
464                 $nextpageparams['action'] = 'grade';
465                 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
466                 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
467             } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
468                 $action = 'redirect';
469                 $nextpageparams['action'] = 'grade';
470                 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
471                 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
472             } else if (optional_param('savegrade', null, PARAM_RAW)) {
473                 // Save changes button.
474                 $action = 'grade';
475                 if ($this->process_save_grade($mform)) {
476                     $action = 'redirect';
477                     $nextpageparams['action'] = 'savegradingresult';
478                 }
479             } else {
480                 // Cancel button.
481                 $action = 'redirect';
482                 $nextpageparams['action'] = 'grading';
483             }
484         } else if ($action == 'quickgrade') {
485             $message = $this->process_save_quick_grades();
486             $action = 'quickgradingresult';
487         } else if ($action == 'saveoptions') {
488             $this->process_save_grading_options();
489             $action = 'redirect';
490             $nextpageparams['action'] = 'grading';
491         } else if ($action == 'saveextension') {
492             $action = 'grantextension';
493             if ($this->process_save_extension($mform)) {
494                 $action = 'redirect';
495                 $nextpageparams['action'] = 'grading';
496             }
497         } else if ($action == 'revealidentitiesconfirm') {
498             $this->process_reveal_identities();
499             $action = 'redirect';
500             $nextpageparams['action'] = 'grading';
501         }
503         $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
504                               'useridlistid'=>optional_param('useridlistid', 0, PARAM_INT));
505         $this->register_return_link($action, $returnparams);
507         // Now show the right view page.
508         if ($action == 'redirect') {
509             $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
510             redirect($nextpageurl);
511             return;
512         } else if ($action == 'savegradingresult') {
513             $message = get_string('gradingchangessaved', 'assign');
514             $o .= $this->view_savegrading_result($message);
515         } else if ($action == 'quickgradingresult') {
516             $mform = null;
517             $o .= $this->view_quickgrading_result($message);
518         } else if ($action == 'grade') {
519             $o .= $this->view_single_grade_page($mform);
520         } else if ($action == 'viewpluginassignfeedback') {
521             $o .= $this->view_plugin_content('assignfeedback');
522         } else if ($action == 'viewpluginassignsubmission') {
523             $o .= $this->view_plugin_content('assignsubmission');
524         } else if ($action == 'editsubmission') {
525             $o .= $this->view_edit_submission_page($mform, $notices);
526         } else if ($action == 'grading') {
527             $o .= $this->view_grading_page();
528         } else if ($action == 'downloadall') {
529             $o .= $this->download_submissions();
530         } else if ($action == 'submit') {
531             $o .= $this->check_submit_for_grading($mform);
532         } else if ($action == 'grantextension') {
533             $o .= $this->view_grant_extension($mform);
534         } else if ($action == 'revealidentities') {
535             $o .= $this->view_reveal_identities_confirm($mform);
536         } else if ($action == 'plugingradingbatchoperation') {
537             $o .= $this->view_plugin_grading_batch_operation($mform);
538         } else if ($action == 'viewpluginpage') {
539              $o .= $this->view_plugin_page();
540         } else if ($action == 'viewcourseindex') {
541              $o .= $this->view_course_index();
542         } else if ($action == 'viewbatchsetmarkingworkflowstate') {
543              $o .= $this->view_batch_set_workflow_state($mform);
544         } else if ($action == 'viewbatchmarkingallocation') {
545             $o .= $this->view_batch_markingallocation($mform);
546         } else if ($action == 'viewsubmitforgradingerror') {
547             $o .= $this->view_error_page(get_string('submitforgrading', 'assign'), $notices);
548         } else {
549             $o .= $this->view_submission_page();
550         }
552         return $o;
553     }
555     /**
556      * Add this instance to the database.
557      *
558      * @param stdClass $formdata The data submitted from the form
559      * @param bool $callplugins This is used to skip the plugin code
560      *             when upgrading an old assignment to a new one (the plugins get called manually)
561      * @return mixed false if an error occurs or the int id of the new instance
562      */
563     public function add_instance(stdClass $formdata, $callplugins) {
564         global $DB;
565         $adminconfig = $this->get_admin_config();
567         $err = '';
569         // Add the database record.
570         $update = new stdClass();
571         $update->name = $formdata->name;
572         $update->timemodified = time();
573         $update->timecreated = time();
574         $update->course = $formdata->course;
575         $update->courseid = $formdata->course;
576         $update->intro = $formdata->intro;
577         $update->introformat = $formdata->introformat;
578         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
579         $update->submissiondrafts = $formdata->submissiondrafts;
580         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
581         $update->sendnotifications = $formdata->sendnotifications;
582         $update->sendlatenotifications = $formdata->sendlatenotifications;
583         $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
584         if (isset($formdata->sendstudentnotifications)) {
585             $update->sendstudentnotifications = $formdata->sendstudentnotifications;
586         }
587         $update->duedate = $formdata->duedate;
588         $update->cutoffdate = $formdata->cutoffdate;
589         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
590         $update->grade = $formdata->grade;
591         $update->completionsubmit = !empty($formdata->completionsubmit);
592         $update->teamsubmission = $formdata->teamsubmission;
593         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
594         if (isset($formdata->teamsubmissiongroupingid)) {
595             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
596         }
597         $update->blindmarking = $formdata->blindmarking;
598         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
599         if (!empty($formdata->attemptreopenmethod)) {
600             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
601         }
602         if (!empty($formdata->maxattempts)) {
603             $update->maxattempts = $formdata->maxattempts;
604         }
605         $update->markingworkflow = $formdata->markingworkflow;
606         $update->markingallocation = $formdata->markingallocation;
607         if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
608             $update->markingallocation = 0;
609         }
611         $returnid = $DB->insert_record('assign', $update);
612         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
613         // Cache the course record.
614         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
616         $this->save_intro_draft_files($formdata);
618         if ($callplugins) {
619             // Call save_settings hook for submission plugins.
620             foreach ($this->submissionplugins as $plugin) {
621                 if (!$this->update_plugin_instance($plugin, $formdata)) {
622                     print_error($plugin->get_error());
623                     return false;
624                 }
625             }
626             foreach ($this->feedbackplugins as $plugin) {
627                 if (!$this->update_plugin_instance($plugin, $formdata)) {
628                     print_error($plugin->get_error());
629                     return false;
630                 }
631             }
633             // In the case of upgrades the coursemodule has not been set,
634             // so we need to wait before calling these two.
635             $this->update_calendar($formdata->coursemodule);
636             $this->update_gradebook(false, $formdata->coursemodule);
638         }
640         $update = new stdClass();
641         $update->id = $this->get_instance()->id;
642         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
643         $DB->update_record('assign', $update);
645         return $returnid;
646     }
648     /**
649      * Delete all grades from the gradebook for this assignment.
650      *
651      * @return bool
652      */
653     protected function delete_grades() {
654         global $CFG;
656         $result = grade_update('mod/assign',
657                                $this->get_course()->id,
658                                'mod',
659                                'assign',
660                                $this->get_instance()->id,
661                                0,
662                                null,
663                                array('deleted'=>1));
664         return $result == GRADE_UPDATE_OK;
665     }
667     /**
668      * Delete this instance from the database.
669      *
670      * @return bool false if an error occurs
671      */
672     public function delete_instance() {
673         global $DB;
674         $result = true;
676         foreach ($this->submissionplugins as $plugin) {
677             if (!$plugin->delete_instance()) {
678                 print_error($plugin->get_error());
679                 $result = false;
680             }
681         }
682         foreach ($this->feedbackplugins as $plugin) {
683             if (!$plugin->delete_instance()) {
684                 print_error($plugin->get_error());
685                 $result = false;
686             }
687         }
689         // Delete files associated with this assignment.
690         $fs = get_file_storage();
691         if (! $fs->delete_area_files($this->context->id) ) {
692             $result = false;
693         }
695         // Delete_records will throw an exception if it fails - so no need for error checking here.
696         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
697         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
698         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
700         // Delete items from the gradebook.
701         if (! $this->delete_grades()) {
702             $result = false;
703         }
705         // Delete the instance.
706         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
708         return $result;
709     }
711     /**
712      * Actual implementation of the reset course functionality, delete all the
713      * assignment submissions for course $data->courseid.
714      *
715      * @param stdClass $data the data submitted from the reset course.
716      * @return array status array
717      */
718     public function reset_userdata($data) {
719         global $CFG, $DB;
721         $componentstr = get_string('modulenameplural', 'assign');
722         $status = array();
724         $fs = get_file_storage();
725         if (!empty($data->reset_assign_submissions)) {
726             // Delete files associated with this assignment.
727             foreach ($this->submissionplugins as $plugin) {
728                 $fileareas = array();
729                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
730                 $fileareas = $plugin->get_file_areas();
731                 foreach ($fileareas as $filearea => $notused) {
732                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
733                 }
735                 if (!$plugin->delete_instance()) {
736                     $status[] = array('component'=>$componentstr,
737                                       'item'=>get_string('deleteallsubmissions', 'assign'),
738                                       'error'=>$plugin->get_error());
739                 }
740             }
742             foreach ($this->feedbackplugins as $plugin) {
743                 $fileareas = array();
744                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
745                 $fileareas = $plugin->get_file_areas();
746                 foreach ($fileareas as $filearea => $notused) {
747                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
748                 }
750                 if (!$plugin->delete_instance()) {
751                     $status[] = array('component'=>$componentstr,
752                                       'item'=>get_string('deleteallsubmissions', 'assign'),
753                                       'error'=>$plugin->get_error());
754                 }
755             }
757             $assignssql = 'SELECT a.id
758                              FROM {assign} a
759                            WHERE a.course=:course';
760             $params = array('course'=>$data->courseid);
762             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
764             $status[] = array('component'=>$componentstr,
765                               'item'=>get_string('deleteallsubmissions', 'assign'),
766                               'error'=>false);
768             if (!empty($data->reset_gradebook_grades)) {
769                 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
770                 // Remove all grades from gradebook.
771                 require_once($CFG->dirroot.'/mod/assign/lib.php');
772                 assign_reset_gradebook($data->courseid);
774                 // Reset revealidentities if both submissions and grades have been reset.
775                 if ($this->get_instance()->blindmarking && $this->get_instance()->revealidentities) {
776                     $DB->set_field('assign', 'revealidentities', 0, array('id' => $this->get_instance()->id));
777                 }
778             }
779         }
780         // Updating dates - shift may be negative too.
781         if ($data->timeshift) {
782             shift_course_mod_dates('assign',
783                                     array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
784                                     $data->timeshift,
785                                     $data->courseid, $this->get_instance()->id);
786             $status[] = array('component'=>$componentstr,
787                               'item'=>get_string('datechanged'),
788                               'error'=>false);
789         }
791         return $status;
792     }
794     /**
795      * Update the settings for a single plugin.
796      *
797      * @param assign_plugin $plugin The plugin to update
798      * @param stdClass $formdata The form data
799      * @return bool false if an error occurs
800      */
801     protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
802         if ($plugin->is_visible()) {
803             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
804             if (!empty($formdata->$enabledname)) {
805                 $plugin->enable();
806                 if (!$plugin->save_settings($formdata)) {
807                     print_error($plugin->get_error());
808                     return false;
809                 }
810             } else {
811                 $plugin->disable();
812             }
813         }
814         return true;
815     }
817     /**
818      * Update the gradebook information for this assignment.
819      *
820      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
821      * @param int $coursemoduleid This is required because it might not exist in the database yet
822      * @return bool
823      */
824     public function update_gradebook($reset, $coursemoduleid) {
825         global $CFG;
827         require_once($CFG->dirroot.'/mod/assign/lib.php');
828         $assign = clone $this->get_instance();
829         $assign->cmidnumber = $coursemoduleid;
831         // Set assign gradebook feedback plugin status (enabled and visible).
832         $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
834         $param = null;
835         if ($reset) {
836             $param = 'reset';
837         }
839         return assign_grade_item_update($assign, $param);
840     }
842     /**
843      * Load and cache the admin config for this module.
844      *
845      * @return stdClass the plugin config
846      */
847     public function get_admin_config() {
848         if ($this->adminconfig) {
849             return $this->adminconfig;
850         }
851         $this->adminconfig = get_config('assign');
852         return $this->adminconfig;
853     }
855     /**
856      * Update the calendar entries for this assignment.
857      *
858      * @param int $coursemoduleid - Required to pass this in because it might
859      *                              not exist in the database yet.
860      * @return bool
861      */
862     public function update_calendar($coursemoduleid) {
863         global $DB, $CFG;
864         require_once($CFG->dirroot.'/calendar/lib.php');
866         // Special case for add_instance as the coursemodule has not been set yet.
867         $instance = $this->get_instance();
869         if ($instance->duedate) {
870             $event = new stdClass();
872             $params = array('modulename'=>'assign', 'instance'=>$instance->id);
873             $event->id = $DB->get_field('event', 'id', $params);
874             $event->name = $instance->name;
875             $event->timestart = $instance->duedate;
877             // Convert the links to pluginfile. It is a bit hacky but at this stage the files
878             // might not have been saved in the module area yet.
879             $intro = $instance->intro;
880             if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
881                 $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
882             }
884             // We need to remove the links to files as the calendar is not ready
885             // to support module events with file areas.
886             $intro = strip_pluginfile_content($intro);
887             if ($this->show_intro()) {
888                 $event->description = array(
889                     'text' => $intro,
890                     'format' => $instance->introformat
891                 );
892             } else {
893                 $event->description = array(
894                     'text' => '',
895                     'format' => $instance->introformat
896                 );
897             }
899             if ($event->id) {
900                 $calendarevent = calendar_event::load($event->id);
901                 $calendarevent->update($event);
902             } else {
903                 unset($event->id);
904                 $event->courseid    = $instance->course;
905                 $event->groupid     = 0;
906                 $event->userid      = 0;
907                 $event->modulename  = 'assign';
908                 $event->instance    = $instance->id;
909                 $event->eventtype   = 'due';
910                 $event->timeduration = 0;
911                 calendar_event::create($event);
912             }
913         } else {
914             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
915         }
916     }
919     /**
920      * Update this instance in the database.
921      *
922      * @param stdClass $formdata - the data submitted from the form
923      * @return bool false if an error occurs
924      */
925     public function update_instance($formdata) {
926         global $DB;
927         $adminconfig = $this->get_admin_config();
929         $update = new stdClass();
930         $update->id = $formdata->instance;
931         $update->name = $formdata->name;
932         $update->timemodified = time();
933         $update->course = $formdata->course;
934         $update->intro = $formdata->intro;
935         $update->introformat = $formdata->introformat;
936         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
937         $update->submissiondrafts = $formdata->submissiondrafts;
938         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
939         $update->sendnotifications = $formdata->sendnotifications;
940         $update->sendlatenotifications = $formdata->sendlatenotifications;
941         $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
942         if (isset($formdata->sendstudentnotifications)) {
943             $update->sendstudentnotifications = $formdata->sendstudentnotifications;
944         }
945         $update->duedate = $formdata->duedate;
946         $update->cutoffdate = $formdata->cutoffdate;
947         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
948         $update->grade = $formdata->grade;
949         if (!empty($formdata->completionunlocked)) {
950             $update->completionsubmit = !empty($formdata->completionsubmit);
951         }
952         $update->teamsubmission = $formdata->teamsubmission;
953         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
954         if (isset($formdata->teamsubmissiongroupingid)) {
955             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
956         }
957         $update->blindmarking = $formdata->blindmarking;
958         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
959         if (!empty($formdata->attemptreopenmethod)) {
960             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
961         }
962         if (!empty($formdata->maxattempts)) {
963             $update->maxattempts = $formdata->maxattempts;
964         }
965         $update->markingworkflow = $formdata->markingworkflow;
966         $update->markingallocation = $formdata->markingallocation;
967         if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
968             $update->markingallocation = 0;
969         }
971         $result = $DB->update_record('assign', $update);
972         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
974         $this->save_intro_draft_files($formdata);
976         // Load the assignment so the plugins have access to it.
978         // Call save_settings hook for submission plugins.
979         foreach ($this->submissionplugins as $plugin) {
980             if (!$this->update_plugin_instance($plugin, $formdata)) {
981                 print_error($plugin->get_error());
982                 return false;
983             }
984         }
985         foreach ($this->feedbackplugins as $plugin) {
986             if (!$this->update_plugin_instance($plugin, $formdata)) {
987                 print_error($plugin->get_error());
988                 return false;
989             }
990         }
992         $this->update_calendar($this->get_course_module()->id);
993         $this->update_gradebook(false, $this->get_course_module()->id);
995         $update = new stdClass();
996         $update->id = $this->get_instance()->id;
997         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
998         $DB->update_record('assign', $update);
1000         return $result;
1001     }
1003     /**
1004      * Save the attachments in the draft areas.
1005      *
1006      * @param stdClass $formdata
1007      */
1008     protected function save_intro_draft_files($formdata) {
1009         if (isset($formdata->introattachments)) {
1010             file_save_draft_area_files($formdata->introattachments, $this->get_context()->id,
1011                                        'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0);
1012         }
1013     }
1015     /**
1016      * Add elements in grading plugin form.
1017      *
1018      * @param mixed $grade stdClass|null
1019      * @param MoodleQuickForm $mform
1020      * @param stdClass $data
1021      * @param int $userid - The userid we are grading
1022      * @return void
1023      */
1024     protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
1025         foreach ($this->feedbackplugins as $plugin) {
1026             if ($plugin->is_enabled() && $plugin->is_visible()) {
1027                 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
1028             }
1029         }
1030     }
1034     /**
1035      * Add one plugins settings to edit plugin form.
1036      *
1037      * @param assign_plugin $plugin The plugin to add the settings from
1038      * @param MoodleQuickForm $mform The form to add the configuration settings to.
1039      *                               This form is modified directly (not returned).
1040      * @param array $pluginsenabled A list of form elements to be added to a group.
1041      *                              The new element is added to this array by this function.
1042      * @return void
1043      */
1044     protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
1045         global $CFG;
1046         if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
1047             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1048             $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
1049             $mform->setType($name, PARAM_BOOL);
1050             $plugin->get_settings($mform);
1051         } else if ($plugin->is_visible() && $plugin->is_configurable()) {
1052             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1053             $label = $plugin->get_name();
1054             $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
1055             $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
1057             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
1058             if ($plugin->get_config('enabled') !== false) {
1059                 $default = $plugin->is_enabled();
1060             }
1061             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
1063             $plugin->get_settings($mform);
1065         }
1066     }
1068     /**
1069      * Add settings to edit plugin form.
1070      *
1071      * @param MoodleQuickForm $mform The form to add the configuration settings to.
1072      *                               This form is modified directly (not returned).
1073      * @return void
1074      */
1075     public function add_all_plugin_settings(MoodleQuickForm $mform) {
1076         $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
1078         $submissionpluginsenabled = array();
1079         $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1080         foreach ($this->submissionplugins as $plugin) {
1081             $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1082         }
1083         $group->setElements($submissionpluginsenabled);
1085         $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1086         $feedbackpluginsenabled = array();
1087         $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1088         foreach ($this->feedbackplugins as $plugin) {
1089             $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1090         }
1091         $group->setElements($feedbackpluginsenabled);
1092         $mform->setExpanded('submissiontypes');
1093     }
1095     /**
1096      * Allow each plugin an opportunity to update the defaultvalues
1097      * passed in to the settings form (needed to set up draft areas for
1098      * editor and filemanager elements)
1099      *
1100      * @param array $defaultvalues
1101      */
1102     public function plugin_data_preprocessing(&$defaultvalues) {
1103         foreach ($this->submissionplugins as $plugin) {
1104             if ($plugin->is_visible()) {
1105                 $plugin->data_preprocessing($defaultvalues);
1106             }
1107         }
1108         foreach ($this->feedbackplugins as $plugin) {
1109             if ($plugin->is_visible()) {
1110                 $plugin->data_preprocessing($defaultvalues);
1111             }
1112         }
1113     }
1115     /**
1116      * Get the name of the current module.
1117      *
1118      * @return string the module name (Assignment)
1119      */
1120     protected function get_module_name() {
1121         if (isset(self::$modulename)) {
1122             return self::$modulename;
1123         }
1124         self::$modulename = get_string('modulename', 'assign');
1125         return self::$modulename;
1126     }
1128     /**
1129      * Get the plural name of the current module.
1130      *
1131      * @return string the module name plural (Assignments)
1132      */
1133     protected function get_module_name_plural() {
1134         if (isset(self::$modulenameplural)) {
1135             return self::$modulenameplural;
1136         }
1137         self::$modulenameplural = get_string('modulenameplural', 'assign');
1138         return self::$modulenameplural;
1139     }
1141     /**
1142      * Has this assignment been constructed from an instance?
1143      *
1144      * @return bool
1145      */
1146     public function has_instance() {
1147         return $this->instance || $this->get_course_module();
1148     }
1150     /**
1151      * Get the settings for the current instance of this assignment
1152      *
1153      * @return stdClass The settings
1154      */
1155     public function get_instance() {
1156         global $DB;
1157         if ($this->instance) {
1158             return $this->instance;
1159         }
1160         if ($this->get_course_module()) {
1161             $params = array('id' => $this->get_course_module()->instance);
1162             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1163         }
1164         if (!$this->instance) {
1165             throw new coding_exception('Improper use of the assignment class. ' .
1166                                        'Cannot load the assignment record.');
1167         }
1168         return $this->instance;
1169     }
1171     /**
1172      * Get the primary grade item for this assign instance.
1173      *
1174      * @return stdClass The grade_item record
1175      */
1176     public function get_grade_item() {
1177         if ($this->gradeitem) {
1178             return $this->gradeitem;
1179         }
1180         $instance = $this->get_instance();
1181         $params = array('itemtype' => 'mod',
1182                         'itemmodule' => 'assign',
1183                         'iteminstance' => $instance->id,
1184                         'courseid' => $instance->course,
1185                         'itemnumber' => 0);
1186         $this->gradeitem = grade_item::fetch($params);
1187         if (!$this->gradeitem) {
1188             throw new coding_exception('Improper use of the assignment class. ' .
1189                                        'Cannot load the grade item.');
1190         }
1191         return $this->gradeitem;
1192     }
1194     /**
1195      * Get the context of the current course.
1196      *
1197      * @return mixed context|null The course context
1198      */
1199     public function get_course_context() {
1200         if (!$this->context && !$this->course) {
1201             throw new coding_exception('Improper use of the assignment class. ' .
1202                                        'Cannot load the course context.');
1203         }
1204         if ($this->context) {
1205             return $this->context->get_course_context();
1206         } else {
1207             return context_course::instance($this->course->id);
1208         }
1209     }
1212     /**
1213      * Get the current course module.
1214      *
1215      * @return cm_info|null The course module or null if not known
1216      */
1217     public function get_course_module() {
1218         if ($this->coursemodule) {
1219             return $this->coursemodule;
1220         }
1221         if (!$this->context) {
1222             return null;
1223         }
1225         if ($this->context->contextlevel == CONTEXT_MODULE) {
1226             $modinfo = get_fast_modinfo($this->get_course());
1227             $this->coursemodule = $modinfo->get_cm($this->context->instanceid);
1228             return $this->coursemodule;
1229         }
1230         return null;
1231     }
1233     /**
1234      * Get context module.
1235      *
1236      * @return context
1237      */
1238     public function get_context() {
1239         return $this->context;
1240     }
1242     /**
1243      * Get the current course.
1244      *
1245      * @return mixed stdClass|null The course
1246      */
1247     public function get_course() {
1248         global $DB;
1250         if ($this->course) {
1251             return $this->course;
1252         }
1254         if (!$this->context) {
1255             return null;
1256         }
1257         $params = array('id' => $this->get_course_context()->instanceid);
1258         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1260         return $this->course;
1261     }
1263     /**
1264      * Count the number of intro attachments.
1265      *
1266      * @return int
1267      */
1268     protected function count_attachments() {
1270         $fs = get_file_storage();
1271         $files = $fs->get_area_files($this->get_context()->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA,
1272                         0, 'id', false);
1274         return count($files);
1275     }
1277     /**
1278      * Are there any intro attachments to display?
1279      *
1280      * @return boolean
1281      */
1282     protected function has_visible_attachments() {
1283         return ($this->count_attachments() > 0);
1284     }
1286     /**
1287      * Return a grade in user-friendly form, whether it's a scale or not.
1288      *
1289      * @param mixed $grade int|null
1290      * @param boolean $editing Are we allowing changes to this grade?
1291      * @param int $userid The user id the grade belongs to
1292      * @param int $modified Timestamp from when the grade was last modified
1293      * @return string User-friendly representation of grade
1294      */
1295     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1296         global $DB;
1298         static $scalegrades = array();
1300         $o = '';
1302         if ($this->get_instance()->grade >= 0) {
1303             // Normal number.
1304             if ($editing && $this->get_instance()->grade > 0) {
1305                 if ($grade < 0) {
1306                     $displaygrade = '';
1307                 } else {
1308                     $displaygrade = format_float($grade, 2);
1309                 }
1310                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1311                        get_string('usergrade', 'assign') .
1312                        '</label>';
1313                 $o .= '<input type="text"
1314                               id="quickgrade_' . $userid . '"
1315                               name="quickgrade_' . $userid . '"
1316                               value="' .  $displaygrade . '"
1317                               size="6"
1318                               maxlength="10"
1319                               class="quickgrade"/>';
1320                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1321                 return $o;
1322             } else {
1323                 if ($grade == -1 || $grade === null) {
1324                     $o .= '-';
1325                 } else {
1326                     $item = $this->get_grade_item();
1327                     $o .= grade_format_gradevalue($grade, $item);
1328                     if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1329                         // If displaying the raw grade, also display the total value.
1330                         $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1331                     }
1332                 }
1333                 return $o;
1334             }
1336         } else {
1337             // Scale.
1338             if (empty($this->cache['scale'])) {
1339                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1340                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1341                 } else {
1342                     $o .= '-';
1343                     return $o;
1344                 }
1345             }
1346             if ($editing) {
1347                 $o .= '<label class="accesshide"
1348                               for="quickgrade_' . $userid . '">' .
1349                       get_string('usergrade', 'assign') .
1350                       '</label>';
1351                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1352                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1353                 foreach ($this->cache['scale'] as $optionid => $option) {
1354                     $selected = '';
1355                     if ($grade == $optionid) {
1356                         $selected = 'selected="selected"';
1357                     }
1358                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1359                 }
1360                 $o .= '</select>';
1361                 return $o;
1362             } else {
1363                 $scaleid = (int)$grade;
1364                 if (isset($this->cache['scale'][$scaleid])) {
1365                     $o .= $this->cache['scale'][$scaleid];
1366                     return $o;
1367                 }
1368                 $o .= '-';
1369                 return $o;
1370             }
1371         }
1372     }
1374     /**
1375      * Load a list of users enrolled in the current course with the specified permission and group.
1376      * 0 for no group.
1377      *
1378      * @param int $currentgroup
1379      * @param bool $idsonly
1380      * @return array List of user records
1381      */
1382     public function list_participants($currentgroup, $idsonly) {
1383         $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
1384         if (!isset($this->participants[$key])) {
1385             $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', null, null, null,
1386                     $this->show_only_active_users());
1388             $cm = $this->get_course_module();
1389             $info = new \core_availability\info_module($cm);
1390             $users = $info->filter_user_list($users);
1392             $this->participants[$key] = $users;
1393         }
1395         if ($idsonly) {
1396             $idslist = array();
1397             foreach ($this->participants[$key] as $id => $user) {
1398                 $idslist[$id] = new stdClass();
1399                 $idslist[$id]->id = $id;
1400             }
1401             return $idslist;
1402         }
1403         return $this->participants[$key];
1404     }
1406     /**
1407      * Load a count of valid teams for this assignment.
1408      *
1409      * @return int number of valid teams
1410      */
1411     public function count_teams() {
1413         if ($currentgroup = groups_get_activity_group($this->get_course_module())) {
1414             return 1;
1415         }
1417         $groups = groups_get_all_groups($this->get_course()->id,
1418                                         0,
1419                                         $this->get_instance()->teamsubmissiongroupingid,
1420                                         'g.id');
1421         $count = count($groups);
1423         // See if there are any users in the default group.
1424         $defaultusers = $this->get_submission_group_members(0, true);
1425         if (count($defaultusers) > 0) {
1426             $count += 1;
1427         }
1428         return $count;
1429     }
1431     /**
1432      * Load a count of active users enrolled in the current course with the specified permission and group.
1433      * 0 for no group.
1434      *
1435      * @param int $currentgroup
1436      * @return int number of matching users
1437      */
1438     public function count_participants($currentgroup) {
1439         return count($this->list_participants($currentgroup, true));
1440     }
1442     /**
1443      * Load a count of active users submissions in the current module that require grading
1444      * This means the submission modification time is more recent than the
1445      * grading modification time and the status is SUBMITTED.
1446      *
1447      * @return int number of matching submissions
1448      */
1449     public function count_submissions_need_grading() {
1450         global $DB;
1452         if ($this->get_instance()->teamsubmission) {
1453             // This does not make sense for group assignment because the submission is shared.
1454             return 0;
1455         }
1457         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1458         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1460         $params['assignid'] = $this->get_instance()->id;
1461         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1463         $sql = 'SELECT COUNT(s.userid)
1464                    FROM {assign_submission} s
1465                    LEFT JOIN {assign_grades} g ON
1466                         s.assignment = g.assignment AND
1467                         s.userid = g.userid AND
1468                         g.attemptnumber = s.attemptnumber
1469                    JOIN(' . $esql . ') e ON e.id = s.userid
1470                    WHERE
1471                         s.latest = 1 AND
1472                         s.assignment = :assignid AND
1473                         s.timemodified IS NOT NULL AND
1474                         s.status = :submitted AND
1475                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1477         return $DB->count_records_sql($sql, $params);
1478     }
1480     /**
1481      * Load a count of grades.
1482      *
1483      * @return int number of grades
1484      */
1485     public function count_grades() {
1486         global $DB;
1488         if (!$this->has_instance()) {
1489             return 0;
1490         }
1492         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1493         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1495         $params['assignid'] = $this->get_instance()->id;
1497         $sql = 'SELECT COUNT(g.userid)
1498                    FROM {assign_grades} g
1499                    JOIN(' . $esql . ') e ON e.id = g.userid
1500                    WHERE g.assignment = :assignid';
1502         return $DB->count_records_sql($sql, $params);
1503     }
1505     /**
1506      * Load a count of submissions.
1507      *
1508      * @param bool $includenew When true, also counts the submissions with status 'new'.
1509      * @return int number of submissions
1510      */
1511     public function count_submissions($includenew = false) {
1512         global $DB;
1514         if (!$this->has_instance()) {
1515             return 0;
1516         }
1518         $params = array();
1519         $sqlnew = '';
1521         if (!$includenew) {
1522             $sqlnew = ' AND s.status <> :status ';
1523             $params['status'] = ASSIGN_SUBMISSION_STATUS_NEW;
1524         }
1526         if ($this->get_instance()->teamsubmission) {
1527             // We cannot join on the enrolment tables for group submissions (no userid).
1528             $sql = 'SELECT COUNT(DISTINCT s.groupid)
1529                         FROM {assign_submission} s
1530                         WHERE
1531                             s.assignment = :assignid AND
1532                             s.timemodified IS NOT NULL AND
1533                             s.userid = :groupuserid' .
1534                             $sqlnew;
1536             $params['assignid'] = $this->get_instance()->id;
1537             $params['groupuserid'] = 0;
1538         } else {
1539             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1540             list($esql, $enrolparams) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1542             $params = array_merge($params, $enrolparams);
1543             $params['assignid'] = $this->get_instance()->id;
1545             $sql = 'SELECT COUNT(DISTINCT s.userid)
1546                        FROM {assign_submission} s
1547                        JOIN(' . $esql . ') e ON e.id = s.userid
1548                        WHERE
1549                             s.assignment = :assignid AND
1550                             s.timemodified IS NOT NULL ' .
1551                             $sqlnew;
1553         }
1555         return $DB->count_records_sql($sql, $params);
1556     }
1558     /**
1559      * Load a count of submissions with a specified status.
1560      *
1561      * @param string $status The submission status - should match one of the constants
1562      * @return int number of matching submissions
1563      */
1564     public function count_submissions_with_status($status) {
1565         global $DB;
1567         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1568         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1570         $params['assignid'] = $this->get_instance()->id;
1571         $params['assignid2'] = $this->get_instance()->id;
1572         $params['submissionstatus'] = $status;
1574         if ($this->get_instance()->teamsubmission) {
1576             $groupstr = '';
1577             if ($currentgroup != NOGROUPS) {
1578                 $groupstr = 's.groupid = :groupid AND';
1579                 $params['groupid'] = $currentgroup;
1580             }
1581             $sql = 'SELECT COUNT(s.groupid)
1582                         FROM {assign_submission} s
1583                         WHERE
1584                             s.latest = 1 AND
1585                             s.assignment = :assignid AND
1586                             s.timemodified IS NOT NULL AND
1587                             s.userid = :groupuserid AND
1588                             ' . $groupstr . '
1589                             s.status = :submissionstatus';
1590             $params['groupuserid'] = 0;
1591         } else {
1592             $sql = 'SELECT COUNT(s.userid)
1593                         FROM {assign_submission} s
1594                         JOIN(' . $esql . ') e ON e.id = s.userid
1595                         WHERE
1596                             s.latest = 1 AND
1597                             s.assignment = :assignid AND
1598                             s.timemodified IS NOT NULL AND
1599                             s.status = :submissionstatus';
1601         }
1603         return $DB->count_records_sql($sql, $params);
1604     }
1606     /**
1607      * Utility function to get the userid for every row in the grading table
1608      * so the order can be frozen while we iterate it.
1609      *
1610      * @return array An array of userids
1611      */
1612     protected function get_grading_userid_list() {
1613         $filter = get_user_preferences('assign_filter', '');
1614         $table = new assign_grading_table($this, 0, $filter, 0, false);
1616         $useridlist = $table->get_column_data('userid');
1618         return $useridlist;
1619     }
1621     /**
1622      * Generate zip file from array of given files.
1623      *
1624      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1625      *                                 This array is indexed by the final file name and each
1626      *                                 element in the array is an instance of a stored_file object.
1627      * @return path of temp file - note this returned file does
1628      *         not have a .zip extension - it is a temp file.
1629      */
1630     protected function pack_files($filesforzipping) {
1631         global $CFG;
1632         // Create path for new zip file.
1633         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1634         // Zip files.
1635         $zipper = new zip_packer();
1636         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1637             return $tempzip;
1638         }
1639         return false;
1640     }
1642     /**
1643      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1644      *
1645      * Cron function to be run periodically according to the moodle cron.
1646      *
1647      * @return bool
1648      */
1649     public static function cron() {
1650         global $DB;
1652         // Only ever send a max of one days worth of updates.
1653         $yesterday = time() - (24 * 3600);
1654         $timenow   = time();
1655         $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
1657         // Collect all submissions from the past 24 hours that require mailing.
1658         // Submissions are excluded if the assignment is hidden in the gradebook.
1659         $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
1660                        g.*, g.timemodified as lastmodified, cm.id as cmid
1661                  FROM {assign} a
1662                  JOIN {assign_grades} g ON g.assignment = a.id
1663             LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1664                  JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id
1665                  JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'
1666                  JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
1667                  WHERE g.timemodified >= :yesterday AND
1668                        g.timemodified <= :today AND
1669                        uf.mailed = 0 AND gri.hidden = 0
1670               ORDER BY a.course, cm.id";
1672         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1673         $submissions = $DB->get_records_sql($sql, $params);
1675         if (!empty($submissions)) {
1677             mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1679             // Preload courses we are going to need those.
1680             $courseids = array();
1681             foreach ($submissions as $submission) {
1682                 $courseids[] = $submission->course;
1683             }
1685             // Filter out duplicates.
1686             $courseids = array_unique($courseids);
1687             $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1688             list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1689             $sql = 'SELECT c.*, ' . $ctxselect .
1690                       ' FROM {course} c
1691                  LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1692                      WHERE c.id ' . $courseidsql;
1694             $params['contextlevel'] = CONTEXT_COURSE;
1695             $courses = $DB->get_records_sql($sql, $params);
1697             // Clean up... this could go on for a while.
1698             unset($courseids);
1699             unset($ctxselect);
1700             unset($courseidsql);
1701             unset($params);
1703             // Message students about new feedback.
1704             foreach ($submissions as $submission) {
1706                 mtrace("Processing assignment submission $submission->id ...");
1708                 // Do not cache user lookups - could be too many.
1709                 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1710                     mtrace('Could not find user ' . $submission->userid);
1711                     continue;
1712                 }
1714                 // Use a cache to prevent the same DB queries happening over and over.
1715                 if (!array_key_exists($submission->course, $courses)) {
1716                     mtrace('Could not find course ' . $submission->course);
1717                     continue;
1718                 }
1719                 $course = $courses[$submission->course];
1720                 if (isset($course->ctxid)) {
1721                     // Context has not yet been preloaded. Do so now.
1722                     context_helper::preload_from_record($course);
1723                 }
1725                 // Override the language and timezone of the "current" user, so that
1726                 // mail is customised for the receiver.
1727                 cron_setup_user($user, $course);
1729                 // Context lookups are already cached.
1730                 $coursecontext = context_course::instance($course->id);
1731                 if (!is_enrolled($coursecontext, $user->id)) {
1732                     $courseshortname = format_string($course->shortname,
1733                                                      true,
1734                                                      array('context' => $coursecontext));
1735                     mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1736                     continue;
1737                 }
1739                 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1740                     mtrace('Could not find grader ' . $submission->grader);
1741                     continue;
1742                 }
1744                 $modinfo = get_fast_modinfo($course, $user->id);
1745                 $cm = $modinfo->get_cm($submission->cmid);
1746                 // Context lookups are already cached.
1747                 $contextmodule = context_module::instance($cm->id);
1749                 if (!$cm->uservisible) {
1750                     // Hold mail notification for assignments the user cannot access until later.
1751                     continue;
1752                 }
1754                 // Need to send this to the student.
1755                 $messagetype = 'feedbackavailable';
1756                 $eventtype = 'assign_notification';
1757                 $updatetime = $submission->lastmodified;
1758                 $modulename = get_string('modulename', 'assign');
1760                 $uniqueid = 0;
1761                 if ($submission->blindmarking && !$submission->revealidentities) {
1762                     $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1763                 }
1764                 $showusers = $submission->blindmarking && !$submission->revealidentities;
1765                 self::send_assignment_notification($grader,
1766                                                    $user,
1767                                                    $messagetype,
1768                                                    $eventtype,
1769                                                    $updatetime,
1770                                                    $cm,
1771                                                    $contextmodule,
1772                                                    $course,
1773                                                    $modulename,
1774                                                    $submission->name,
1775                                                    $showusers,
1776                                                    $uniqueid);
1778                 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1779                 if ($flags) {
1780                     $flags->mailed = 1;
1781                     $DB->update_record('assign_user_flags', $flags);
1782                 } else {
1783                     $flags = new stdClass();
1784                     $flags->userid = $user->id;
1785                     $flags->assignment = $submission->assignment;
1786                     $flags->mailed = 1;
1787                     $DB->insert_record('assign_user_flags', $flags);
1788                 }
1790                 mtrace('Done');
1791             }
1792             mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1794             cron_setup_user();
1796             // Free up memory just to be sure.
1797             unset($courses);
1798         }
1800         // Update calendar events to provide a description.
1801         $sql = 'SELECT id
1802                     FROM {assign}
1803                     WHERE
1804                         allowsubmissionsfromdate >= :lastcron AND
1805                         allowsubmissionsfromdate <= :timenow AND
1806                         alwaysshowdescription = 0';
1807         $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
1808         $newlyavailable = $DB->get_records_sql($sql, $params);
1809         foreach ($newlyavailable as $record) {
1810             $cm = get_coursemodule_from_instance('assign', $record->id, 0, false, MUST_EXIST);
1811             $context = context_module::instance($cm->id);
1813             $assignment = new assign($context, null, null);
1814             $assignment->update_calendar($cm->id);
1815         }
1817         return true;
1818     }
1820     /**
1821      * Mark in the database that this grade record should have an update notification sent by cron.
1822      *
1823      * @param stdClass $grade a grade record keyed on id
1824      * @return bool true for success
1825      */
1826     public function notify_grade_modified($grade) {
1827         global $DB;
1829         $flags = $this->get_user_flags($grade->userid, true);
1830         if ($flags->mailed != 1) {
1831             $flags->mailed = 0;
1832         }
1834         return $this->update_user_flags($flags);
1835     }
1837     /**
1838      * Update user flags for this user in this assignment.
1839      *
1840      * @param stdClass $flags a flags record keyed on id
1841      * @return bool true for success
1842      */
1843     public function update_user_flags($flags) {
1844         global $DB;
1845         if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1846             return false;
1847         }
1849         $result = $DB->update_record('assign_user_flags', $flags);
1850         return $result;
1851     }
1853     /**
1854      * Update a grade in the grade table for the assignment and in the gradebook.
1855      *
1856      * @param stdClass $grade a grade record keyed on id
1857      * @param bool $reopenattempt If the attempt reopen method is manual, allow another attempt at this assignment.
1858      * @return bool true for success
1859      */
1860     public function update_grade($grade, $reopenattempt = false) {
1861         global $DB;
1863         $grade->timemodified = time();
1865         if (!empty($grade->workflowstate)) {
1866             $validstates = $this->get_marking_workflow_states_for_current_user();
1867             if (!array_key_exists($grade->workflowstate, $validstates)) {
1868                 return false;
1869             }
1870         }
1872         if ($grade->grade && $grade->grade != -1) {
1873             if ($this->get_instance()->grade > 0) {
1874                 if (!is_numeric($grade->grade)) {
1875                     return false;
1876                 } else if ($grade->grade > $this->get_instance()->grade) {
1877                     return false;
1878                 } else if ($grade->grade < 0) {
1879                     return false;
1880                 }
1881             } else {
1882                 // This is a scale.
1883                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1884                     $scaleoptions = make_menu_from_list($scale->scale);
1885                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1886                         return false;
1887                     }
1888                 }
1889             }
1890         }
1892         if (empty($grade->attemptnumber)) {
1893             // Set it to the default.
1894             $grade->attemptnumber = 0;
1895         }
1896         $result = $DB->update_record('assign_grades', $grade);
1898         // If the conditions are met, allow another attempt.
1899         $submission = null;
1900         if ($this->get_instance()->teamsubmission) {
1901             $submission = $this->get_group_submission($grade->userid, 0, false);
1902         } else {
1903             $submission = $this->get_user_submission($grade->userid, false);
1904         }
1905         if ($submission && $submission->attemptnumber == $grade->attemptnumber) {
1906             $this->reopen_submission_if_required($grade->userid,
1907                                                  $submission,
1908                                                  $reopenattempt);
1909         }
1911         // Only push to gradebook if the update is for the latest attempt.
1912         // Not the latest attempt.
1913         if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1914             return true;
1915         }
1917         if ($result) {
1918             $this->gradebook_item_update(null, $grade);
1919             \mod_assign\event\submission_graded::create_from_grade($this, $grade)->trigger();
1920         }
1921         return $result;
1922     }
1924     /**
1925      * View the grant extension date page.
1926      *
1927      * Uses url parameters 'userid'
1928      * or from parameter 'selectedusers'
1929      *
1930      * @param moodleform $mform - Used for validation of the submitted data
1931      * @return string
1932      */
1933     protected function view_grant_extension($mform) {
1934         global $DB, $CFG;
1935         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1937         $o = '';
1938         $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1939         $data = new stdClass();
1940         $data->extensionduedate = null;
1941         $userid = 0;
1942         if (!$batchusers) {
1943             $userid = required_param('userid', PARAM_INT);
1945             $flags = $this->get_user_flags($userid, false);
1947             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1949             if ($flags) {
1950                 $data->extensionduedate = $flags->extensionduedate;
1951             }
1952             $data->userid = $userid;
1953         } else {
1954             $data->batchusers = $batchusers;
1955         }
1956         $header = new assign_header($this->get_instance(),
1957                                     $this->get_context(),
1958                                     $this->show_intro(),
1959                                     $this->get_course_module()->id,
1960                                     get_string('grantextension', 'assign'));
1961         $o .= $this->get_renderer()->render($header);
1963         if (!$mform) {
1964             $formparams = array($this->get_course_module()->id,
1965                                 $userid,
1966                                 $batchusers,
1967                                 $this->get_instance(),
1968                                 $data);
1969             $mform = new mod_assign_extension_form(null, $formparams);
1970         }
1971         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1972         $o .= $this->view_footer();
1973         return $o;
1974     }
1976     /**
1977      * Get a list of the users in the same group as this user.
1978      *
1979      * @param int $groupid The id of the group whose members we want or 0 for the default group
1980      * @param bool $onlyids Whether to retrieve only the user id's
1981      * @return array The users (possibly id's only)
1982      */
1983     public function get_submission_group_members($groupid, $onlyids) {
1984         $members = array();
1985         if ($groupid != 0) {
1986             if ($onlyids) {
1987                 $allusers = groups_get_members($groupid, 'u.id');
1988             } else {
1989                 $allusers = groups_get_members($groupid);
1990             }
1991             foreach ($allusers as $user) {
1992                 if ($this->get_submission_group($user->id)) {
1993                     $members[] = $user;
1994                 }
1995             }
1996         } else {
1997             $allusers = $this->list_participants(null, $onlyids);
1998             foreach ($allusers as $user) {
1999                 if ($this->get_submission_group($user->id) == null) {
2000                     $members[] = $user;
2001                 }
2002             }
2003         }
2004         // Exclude suspended users, if user can't see them.
2005         if (!has_capability('moodle/course:viewsuspendedusers', $this->context)) {
2006             foreach ($members as $key => $member) {
2007                 if (!$this->is_active_user($member->id)) {
2008                     unset($members[$key]);
2009                 }
2010             }
2011         }
2012         return $members;
2013     }
2015     /**
2016      * Get a list of the users in the same group as this user that have not submitted the assignment.
2017      *
2018      * @param int $groupid The id of the group whose members we want or 0 for the default group
2019      * @param bool $onlyids Whether to retrieve only the user id's
2020      * @return array The users (possibly id's only)
2021      */
2022     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
2023         $instance = $this->get_instance();
2024         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
2025             return array();
2026         }
2027         $members = $this->get_submission_group_members($groupid, $onlyids);
2029         foreach ($members as $id => $member) {
2030             $submission = $this->get_user_submission($member->id, false);
2031             if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2032                 unset($members[$id]);
2033             } else {
2034                 if ($this->is_blind_marking()) {
2035                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
2036                                            $this->get_uniqueid_for_user($id);
2037                 }
2038             }
2039         }
2040         return $members;
2041     }
2043     /**
2044      * Load the group submission object for a particular user, optionally creating it if required.
2045      *
2046      * @param int $userid The id of the user whose submission we want
2047      * @param int $groupid The id of the group for this user - may be 0 in which
2048      *                     case it is determined from the userid.
2049      * @param bool $create If set to true a new submission object will be created in the database
2050      *                     with the status set to "new".
2051      * @param int $attemptnumber - -1 means the latest attempt
2052      * @return stdClass The submission
2053      */
2054     public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
2055         global $DB;
2057         if ($groupid == 0) {
2058             $group = $this->get_submission_group($userid);
2059             if ($group) {
2060                 $groupid = $group->id;
2061             }
2062         }
2064         // Now get the group submission.
2065         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2066         if ($attemptnumber >= 0) {
2067             $params['attemptnumber'] = $attemptnumber;
2068         }
2070         // Only return the row with the highest attemptnumber.
2071         $submission = null;
2072         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2073         if ($submissions) {
2074             $submission = reset($submissions);
2075         }
2077         if ($submission) {
2078             return $submission;
2079         }
2080         if ($create) {
2081             $submission = new stdClass();
2082             $submission->assignment = $this->get_instance()->id;
2083             $submission->userid = 0;
2084             $submission->groupid = $groupid;
2085             $submission->timecreated = time();
2086             $submission->timemodified = $submission->timecreated;
2087             if ($attemptnumber >= 0) {
2088                 $submission->attemptnumber = $attemptnumber;
2089             } else {
2090                 $submission->attemptnumber = 0;
2091             }
2092             // Work out if this is the latest submission.
2093             $submission->latest = 0;
2094             $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2095             if ($attemptnumber == -1) {
2096                 // This is a new submission so it must be the latest.
2097                 $submission->latest = 1;
2098             } else {
2099                 // We need to work this out.
2100                 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
2101                 if ($result) {
2102                     $latestsubmission = reset($result);
2103                 }
2104                 if (!$latestsubmission || ($attemptnumber == $latestsubmission->attemptnumber)) {
2105                     $submission->latest = 1;
2106                 }
2107             }
2108             if ($submission->latest) {
2109                 // This is the case when we need to set latest to 0 for all the other attempts.
2110                 $DB->set_field('assign_submission', 'latest', 0, $params);
2111             }
2112             $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
2113             $sid = $DB->insert_record('assign_submission', $submission);
2114             return $DB->get_record('assign_submission', array('id' => $sid));
2115         }
2116         return false;
2117     }
2119     /**
2120      * View a summary listing of all assignments in the current course.
2121      *
2122      * @return string
2123      */
2124     private function view_course_index() {
2125         global $USER;
2127         $o = '';
2129         $course = $this->get_course();
2130         $strplural = get_string('modulenameplural', 'assign');
2132         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2133             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2134             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2135             return $o;
2136         }
2138         $strsectionname = '';
2139         $usesections = course_format_uses_sections($course->format);
2140         $modinfo = get_fast_modinfo($course);
2142         if ($usesections) {
2143             $strsectionname = get_string('sectionname', 'format_'.$course->format);
2144             $sections = $modinfo->get_section_info_all();
2145         }
2146         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2148         $timenow = time();
2150         $currentsection = '';
2151         foreach ($modinfo->instances['assign'] as $cm) {
2152             if (!$cm->uservisible) {
2153                 continue;
2154             }
2156             $timedue = $cms[$cm->id]->duedate;
2158             $sectionname = '';
2159             if ($usesections && $cm->sectionnum) {
2160                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2161             }
2163             $submitted = '';
2164             $context = context_module::instance($cm->id);
2166             $assignment = new assign($context, $cm, $course);
2168             if (has_capability('mod/assign:grade', $context)) {
2169                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2171             } else if (has_capability('mod/assign:submit', $context)) {
2172                 $usersubmission = $assignment->get_user_submission($USER->id, false);
2174                 if (!empty($usersubmission->status)) {
2175                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2176                 } else {
2177                     $submitted = get_string('submissionstatus_', 'assign');
2178                 }
2179             }
2180             $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2181             if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2182                     !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2183                 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2184             } else {
2185                 $grade = '-';
2186             }
2188             $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2190         }
2192         $o .= $this->get_renderer()->render($courseindexsummary);
2193         $o .= $this->view_footer();
2195         return $o;
2196     }
2198     /**
2199      * View a page rendered by a plugin.
2200      *
2201      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2202      *
2203      * @return string
2204      */
2205     protected function view_plugin_page() {
2206         global $USER;
2208         $o = '';
2210         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2211         $plugintype = required_param('plugin', PARAM_TEXT);
2212         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2214         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2215         if (!$plugin) {
2216             print_error('invalidformdata', '');
2217             return;
2218         }
2220         $o .= $plugin->view_page($pluginaction);
2222         return $o;
2223     }
2226     /**
2227      * This is used for team assignments to get the group for the specified user.
2228      * If the user is a member of multiple or no groups this will return false
2229      *
2230      * @param int $userid The id of the user whose submission we want
2231      * @return mixed The group or false
2232      */
2233     public function get_submission_group($userid) {
2234         $grouping = $this->get_instance()->teamsubmissiongroupingid;
2235         $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2236         if (count($groups) != 1) {
2237             return false;
2238         }
2239         return array_pop($groups);
2240     }
2243     /**
2244      * Display the submission that is used by a plugin.
2245      *
2246      * Uses url parameters 'sid', 'gid' and 'plugin'.
2247      *
2248      * @param string $pluginsubtype
2249      * @return string
2250      */
2251     protected function view_plugin_content($pluginsubtype) {
2252         $o = '';
2254         $submissionid = optional_param('sid', 0, PARAM_INT);
2255         $gradeid = optional_param('gid', 0, PARAM_INT);
2256         $plugintype = required_param('plugin', PARAM_TEXT);
2257         $item = null;
2258         if ($pluginsubtype == 'assignsubmission') {
2259             $plugin = $this->get_submission_plugin_by_type($plugintype);
2260             if ($submissionid <= 0) {
2261                 throw new coding_exception('Submission id should not be 0');
2262             }
2263             $item = $this->get_submission($submissionid);
2265             // Check permissions.
2266             $this->require_view_submission($item->userid);
2267             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2268                                                               $this->get_context(),
2269                                                               $this->show_intro(),
2270                                                               $this->get_course_module()->id,
2271                                                               $plugin->get_name()));
2272             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2273                                                               $item,
2274                                                               assign_submission_plugin_submission::FULL,
2275                                                               $this->get_course_module()->id,
2276                                                               $this->get_return_action(),
2277                                                               $this->get_return_params()));
2279             // Trigger event for viewing a submission.
2280             \mod_assign\event\submission_viewed::create_from_submission($this, $item)->trigger();
2282         } else {
2283             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2284             if ($gradeid <= 0) {
2285                 throw new coding_exception('Grade id should not be 0');
2286             }
2287             $item = $this->get_grade($gradeid);
2288             // Check permissions.
2289             $this->require_view_submission($item->userid);
2290             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2291                                                               $this->get_context(),
2292                                                               $this->show_intro(),
2293                                                               $this->get_course_module()->id,
2294                                                               $plugin->get_name()));
2295             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2296                                                               $item,
2297                                                               assign_feedback_plugin_feedback::FULL,
2298                                                               $this->get_course_module()->id,
2299                                                               $this->get_return_action(),
2300                                                               $this->get_return_params()));
2302             // Trigger event for viewing feedback.
2303             \mod_assign\event\feedback_viewed::create_from_grade($this, $item)->trigger();
2304         }
2306         $o .= $this->view_return_links();
2308         $o .= $this->view_footer();
2310         return $o;
2311     }
2313     /**
2314      * Rewrite plugin file urls so they resolve correctly in an exported zip.
2315      *
2316      * @param string $text - The replacement text
2317      * @param stdClass $user - The user record
2318      * @param assign_plugin $plugin - The assignment plugin
2319      */
2320     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2321         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2322         $groupname = '';
2323         if ($groupmode) {
2324             $groupid = groups_get_activity_group($this->get_course_module(), true);
2325             $groupname = groups_get_group_name($groupid).'-';
2326         }
2328         if ($this->is_blind_marking()) {
2329             $prefix = $groupname . get_string('participant', 'assign');
2330             $prefix = str_replace('_', ' ', $prefix);
2331             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2332         } else {
2333             $prefix = $groupname . fullname($user);
2334             $prefix = str_replace('_', ' ', $prefix);
2335             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2336         }
2338         $subtype = $plugin->get_subtype();
2339         $type = $plugin->get_type();
2340         $prefix = $prefix . $subtype . '_' . $type . '_';
2342         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2344         return $result;
2345     }
2347     /**
2348      * Render the content in editor that is often used by plugin.
2349      *
2350      * @param string $filearea
2351      * @param int  $submissionid
2352      * @param string $plugintype
2353      * @param string $editor
2354      * @param string $component
2355      * @return string
2356      */
2357     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2358         global $CFG;
2360         $result = '';
2362         $plugin = $this->get_submission_plugin_by_type($plugintype);
2364         $text = $plugin->get_editor_text($editor, $submissionid);
2365         $format = $plugin->get_editor_format($editor, $submissionid);
2367         $finaltext = file_rewrite_pluginfile_urls($text,
2368                                                   'pluginfile.php',
2369                                                   $this->get_context()->id,
2370                                                   $component,
2371                                                   $filearea,
2372                                                   $submissionid);
2373         $params = array('overflowdiv' => true, 'context' => $this->get_context());
2374         $result .= format_text($finaltext, $format, $params);
2376         if ($CFG->enableportfolios) {
2377             require_once($CFG->libdir . '/portfoliolib.php');
2379             $button = new portfolio_add_button();
2380             $portfolioparams = array('cmid' => $this->get_course_module()->id,
2381                                      'sid' => $submissionid,
2382                                      'plugin' => $plugintype,
2383                                      'editor' => $editor,
2384                                      'area'=>$filearea);
2385             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2386             $fs = get_file_storage();
2388             if ($files = $fs->get_area_files($this->context->id,
2389                                              $component,
2390                                              $filearea,
2391                                              $submissionid,
2392                                              'timemodified',
2393                                              false)) {
2394                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2395             } else {
2396                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2397             }
2398             $result .= $button->to_html();
2399         }
2400         return $result;
2401     }
2403     /**
2404      * Display a continue page after grading.
2405      *
2406      * @param string $message - The message to display.
2407      * @return string
2408      */
2409     protected function view_savegrading_result($message) {
2410         $o = '';
2411         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2412                                                       $this->get_context(),
2413                                                       $this->show_intro(),
2414                                                       $this->get_course_module()->id,
2415                                                       get_string('savegradingresult', 'assign')));
2416         $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2417                                                    $message,
2418                                                    $this->get_course_module()->id);
2419         $o .= $this->get_renderer()->render($gradingresult);
2420         $o .= $this->view_footer();
2421         return $o;
2422     }
2423     /**
2424      * Display a continue page after quickgrading.
2425      *
2426      * @param string $message - The message to display.
2427      * @return string
2428      */
2429     protected function view_quickgrading_result($message) {
2430         $o = '';
2431         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2432                                                       $this->get_context(),
2433                                                       $this->show_intro(),
2434                                                       $this->get_course_module()->id,
2435                                                       get_string('quickgradingresult', 'assign')));
2436         $lastpage = optional_param('lastpage', null, PARAM_INT);
2437         $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2438                                                    $message,
2439                                                    $this->get_course_module()->id,
2440                                                    false,
2441                                                    $lastpage);
2442         $o .= $this->get_renderer()->render($gradingresult);
2443         $o .= $this->view_footer();
2444         return $o;
2445     }
2447     /**
2448      * Display the page footer.
2449      *
2450      * @return string
2451      */
2452     protected function view_footer() {
2453         // When viewing the footer during PHPUNIT tests a set_state error is thrown.
2454         if (!PHPUNIT_TEST) {
2455             return $this->get_renderer()->render_footer();
2456         }
2458         return '';
2459     }
2461     /**
2462      * Throw an error if the permissions to view this users submission are missing.
2463      *
2464      * @throws required_capability_exception
2465      * @return none
2466      */
2467     public function require_view_submission($userid) {
2468         if (!$this->can_view_submission($userid)) {
2469             throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2470         }
2471     }
2473     /**
2474      * Throw an error if the permissions to view grades in this assignment are missing.
2475      *
2476      * @throws required_capability_exception
2477      * @return none
2478      */
2479     public function require_view_grades() {
2480         if (!$this->can_view_grades()) {
2481             throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2482         }
2483     }
2485     /**
2486      * Does this user have view grade or grade permission for this assignment?
2487      *
2488      * @return bool
2489      */
2490     public function can_view_grades() {
2491         // Permissions check.
2492         if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
2493             return false;
2494         }
2496         return true;
2497     }
2499     /**
2500      * Does this user have grade permission for this assignment?
2501      *
2502      * @return bool
2503      */
2504     public function can_grade() {
2505         // Permissions check.
2506         if (!has_capability('mod/assign:grade', $this->context)) {
2507             return false;
2508         }
2510         return true;
2511     }
2513     /**
2514      * Download a zip file of all assignment submissions.
2515      *
2516      * @return string - If an error occurs, this will contain the error page.
2517      */
2518     protected function download_submissions() {
2519         global $CFG, $DB;
2521         // More efficient to load this here.
2522         require_once($CFG->libdir.'/filelib.php');
2524         $this->require_view_grades();
2526         // Load all users with submit.
2527         $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2528                         $this->show_only_active_users());
2530         // Build a list of files to zip.
2531         $filesforzipping = array();
2532         $fs = get_file_storage();
2534         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2535         // All users.
2536         $groupid = 0;
2537         $groupname = '';
2538         if ($groupmode) {
2539             $groupid = groups_get_activity_group($this->get_course_module(), true);
2540             $groupname = groups_get_group_name($groupid).'-';
2541         }
2543         // Construct the zip file name.
2544         $filename = clean_filename($this->get_course()->shortname . '-' .
2545                                    $this->get_instance()->name . '-' .
2546                                    $groupname.$this->get_course_module()->id . '.zip');
2548         // Get all the files for each student.
2549         foreach ($students as $student) {
2550             $userid = $student->id;
2552             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2553                 // Get the plugins to add their own files to the zip.
2555                 $submissiongroup = false;
2556                 $groupname = '';
2557                 if ($this->get_instance()->teamsubmission) {
2558                     $submission = $this->get_group_submission($userid, 0, false);
2559                     $submissiongroup = $this->get_submission_group($userid);
2560                     if ($submissiongroup) {
2561                         $groupname = $submissiongroup->name . '-';
2562                     } else {
2563                         $groupname = get_string('defaultteam', 'assign') . '-';
2564                     }
2565                 } else {
2566                     $submission = $this->get_user_submission($userid, false);
2567                 }
2569                 if ($this->is_blind_marking()) {
2570                     $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2571                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2572                 } else {
2573                     $prefix = str_replace('_', ' ', $groupname . fullname($student));
2574                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2575                 }
2577                 if ($submission) {
2578                     foreach ($this->submissionplugins as $plugin) {
2579                         if ($plugin->is_enabled() && $plugin->is_visible()) {
2580                             $pluginfiles = $plugin->get_files($submission, $student);
2581                             foreach ($pluginfiles as $zipfilename => $file) {
2582                                 $subtype = $plugin->get_subtype();
2583                                 $type = $plugin->get_type();
2584                                 $prefixedfilename = clean_filename($prefix .
2585                                                                    $subtype .
2586                                                                    '_' .
2587                                                                    $type .
2588                                                                    '_' .
2589                                                                    $zipfilename);
2590                                 $filesforzipping[$prefixedfilename] = $file;
2591                             }
2592                         }
2593                     }
2594                 }
2595             }
2596         }
2597         $result = '';
2598         if (count($filesforzipping) == 0) {
2599             $header = new assign_header($this->get_instance(),
2600                                         $this->get_context(),
2601                                         '',
2602                                         $this->get_course_module()->id,
2603                                         get_string('downloadall', 'assign'));
2604             $result .= $this->get_renderer()->render($header);
2605             $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2606             $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2607                                                                     'action'=>'grading'));
2608             $result .= $this->get_renderer()->continue_button($url);
2609             $result .= $this->view_footer();
2610         } else if ($zipfile = $this->pack_files($filesforzipping)) {
2611             \mod_assign\event\all_submissions_downloaded::create_from_assign($this)->trigger();
2612             // Send file and delete after sending.
2613             send_temp_file($zipfile, $filename);
2614             // We will not get here - send_temp_file calls exit.
2615         }
2616         return $result;
2617     }
2619     /**
2620      * Util function to add a message to the log.
2621      *
2622      * @deprecated since 2.7 - Use new events system instead.
2623      *             (see http://docs.moodle.org/dev/Migrating_logging_calls_in_plugins).
2624      *
2625      * @param string $action The current action
2626      * @param string $info A detailed description of the change. But no more than 255 characters.
2627      * @param string $url The url to the assign module instance.
2628      * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2629      *                     retrieve the arguments to use them with the new event system (Event 2).
2630      * @return void|array
2631      */
2632     public function add_to_log($action = '', $info = '', $url='', $return = false) {
2633         global $USER;
2635         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2636         if ($url != '') {
2637             $fullurl .= '&' . $url;
2638         }
2640         $args = array(
2641             $this->get_course()->id,
2642             'assign',
2643             $action,
2644             $fullurl,
2645             $info,
2646             $this->get_course_module()->id
2647         );
2649         if ($return) {
2650             // We only need to call debugging when returning a value. This is because the call to
2651             // call_user_func_array('add_to_log', $args) will trigger a debugging message of it's own.
2652             debugging('The mod_assign add_to_log() function is now deprecated.', DEBUG_DEVELOPER);
2653             return $args;
2654         }
2655         call_user_func_array('add_to_log', $args);
2656     }
2658     /**
2659      * Lazy load the page renderer and expose the renderer to plugins.
2660      *
2661      * @return assign_renderer
2662      */
2663     public function get_renderer() {
2664         global $PAGE;
2665         if ($this->output) {
2666             return $this->output;
2667         }
2668         $this->output = $PAGE->get_renderer('mod_assign');
2669         return $this->output;
2670     }
2672     /**
2673      * Load the submission object for a particular user, optionally creating it if required.
2674      *
2675      * For team assignments there are 2 submissions - the student submission and the team submission
2676      * All files are associated with the team submission but the status of the students contribution is
2677      * recorded separately.
2678      *
2679      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2680      * @param bool $create optional - defaults to false. If set to true a new submission object
2681      *                     will be created in the database with the status set to "new".
2682      * @param int $attemptnumber - -1 means the latest attempt
2683      * @return stdClass The submission
2684      */
2685     public function get_user_submission($userid, $create, $attemptnumber=-1) {
2686         global $DB, $USER;
2688         if (!$userid) {
2689             $userid = $USER->id;
2690         }
2691         // If the userid is not null then use userid.
2692         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2693         if ($attemptnumber >= 0) {
2694             $params['attemptnumber'] = $attemptnumber;
2695         }
2697         // Only return the row with the highest attemptnumber.
2698         $submission = null;
2699         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2700         if ($submissions) {
2701             $submission = reset($submissions);
2702         }
2704         if ($submission) {
2705             return $submission;
2706         }
2707         if ($create) {
2708             $submission = new stdClass();
2709             $submission->assignment   = $this->get_instance()->id;
2710             $submission->userid       = $userid;
2711             $submission->timecreated = time();
2712             $submission->timemodified = $submission->timecreated;
2713             $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
2714             if ($attemptnumber >= 0) {
2715                 $submission->attemptnumber = $attemptnumber;
2716             } else {
2717                 $submission->attemptnumber = 0;
2718             }
2719             // Work out if this is the latest submission.
2720             $submission->latest = 0;
2721             $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2722             if ($attemptnumber == -1) {
2723                 // This is a new submission so it must be the latest.
2724                 $submission->latest = 1;
2725             } else {
2726                 // We need to work this out.
2727                 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
2728                 $latestsubmission = null;
2729                 if ($result) {
2730                     $latestsubmission = reset($result);
2731                 }
2732                 if (empty($latestsubmission) || ($attemptnumber > $latestsubmission->attemptnumber)) {
2733                     $submission->latest = 1;
2734                 }
2735             }
2736             if ($submission->latest) {
2737                 // This is the case when we need to set latest to 0 for all the other attempts.
2738                 $DB->set_field('assign_submission', 'latest', 0, $params);
2739             }
2740             $sid = $DB->insert_record('assign_submission', $submission);
2741             return $DB->get_record('assign_submission', array('id' => $sid));
2742         }
2743         return false;
2744     }
2746     /**
2747      * Load the submission object from it's id.
2748      *
2749      * @param int $submissionid The id of the submission we want
2750      * @return stdClass The submission
2751      */
2752     protected function get_submission($submissionid) {
2753         global $DB;
2755         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2756         return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2757     }
2759     /**
2760      * This will retrieve a user flags object from the db optionally creating it if required.
2761      * The user flags was split from the user_grades table in 2.5.
2762      *
2763      * @param int $userid The user we are getting the flags for.
2764      * @param bool $create If true the flags record will be created if it does not exist
2765      * @return stdClass The flags record
2766      */
2767     public function get_user_flags($userid, $create) {
2768         global $DB, $USER;
2770         // If the userid is not null then use userid.
2771         if (!$userid) {
2772             $userid = $USER->id;
2773         }
2775         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2777         $flags = $DB->get_record('assign_user_flags', $params);
2779         if ($flags) {
2780             return $flags;
2781         }
2782         if ($create) {
2783             $flags = new stdClass();
2784             $flags->assignment = $this->get_instance()->id;
2785             $flags->userid = $userid;
2786             $flags->locked = 0;
2787             $flags->extensionduedate = 0;
2788             $flags->workflowstate = '';
2789             $flags->allocatedmarker = 0;
2791             // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2792             // This is because students only want to be notified about certain types of update (grades and feedback).
2793             $flags->mailed = 2;
2795             $fid = $DB->insert_record('assign_user_flags', $flags);
2796             $flags->id = $fid;
2797             return $flags;
2798         }
2799         return false;
2800     }
2802     /**
2803      * This will retrieve a grade object from the db, optionally creating it if required.
2804      *
2805      * @param int $userid The user we are grading
2806      * @param bool $create If true the grade will be created if it does not exist
2807      * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2808      * @return stdClass The grade record
2809      */
2810     public function get_user_grade($userid, $create, $attemptnumber=-1) {
2811         global $DB, $USER;
2813         // If the userid is not null then use userid.
2814         if (!$userid) {
2815             $userid = $USER->id;
2816         }
2818         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2819         if ($attemptnumber < 0) {
2820             // Make sure this grade matches the latest submission attempt.
2821             if ($this->get_instance()->teamsubmission) {
2822                 $submission = $this->get_group_submission($userid, 0, true);
2823             } else {
2824                 $submission = $this->get_user_submission($userid, true);
2825             }
2826             if ($submission) {
2827                 $attemptnumber = $submission->attemptnumber;
2828             }
2829         }
2831         if ($attemptnumber >= 0) {
2832             $params['attemptnumber'] = $attemptnumber;
2833         }
2835         $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2837         if ($grades) {
2838             return reset($grades);
2839         }
2840         if ($create) {
2841             $grade = new stdClass();
2842             $grade->assignment   = $this->get_instance()->id;
2843             $grade->userid       = $userid;
2844             $grade->timecreated = time();
2845             $grade->timemodified = $grade->timecreated;
2846             $grade->grade = -1;
2847             $grade->grader = $USER->id;
2848             if ($attemptnumber >= 0) {
2849                 $grade->attemptnumber = $attemptnumber;
2850             }
2852             $gid = $DB->insert_record('assign_grades', $grade);
2853             $grade->id = $gid;
2854             return $grade;
2855         }
2856         return false;
2857     }
2859     /**
2860      * This will retrieve a grade object from the db.
2861      *
2862      * @param int $gradeid The id of the grade
2863      * @return stdClass The grade record
2864      */
2865     protected function get_grade($gradeid) {
2866         global $DB;
2868         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2869         return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2870     }
2872     /**
2873      * Print the grading page for a single user submission.
2874      *
2875      * @param moodleform $mform
2876      * @return string
2877      */
2878     protected function view_single_grade_page($mform) {
2879         global $DB, $CFG;
2881         $o = '';
2882         $instance = $this->get_instance();
2884         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2886         // Need submit permission to submit an assignment.
2887         require_capability('mod/assign:grade', $this->context);
2889         $header = new assign_header($instance,
2890                                     $this->get_context(),
2891                                     false,
2892                                     $this->get_course_module()->id,
2893                                     get_string('grading', 'assign'));
2894         $o .= $this->get_renderer()->render($header);
2896         // If userid is passed - we are only grading a single student.
2897         $rownum = required_param('rownum', PARAM_INT);
2898         $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2899         $userid = optional_param('userid', 0, PARAM_INT);
2900         $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2902         $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2903         if (!$userid) {
2904             if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2905                 $useridlist = $this->get_grading_userid_list();
2906             }
2907             $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2908         } else {
2909             $rownum = 0;
2910             $useridlist = array($userid);
2911         }
2913         if ($rownum < 0 || $rownum > count($useridlist)) {
2914             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2915         }
2917         $last = false;
2918         $userid = $useridlist[$rownum];
2919         if ($rownum == count($useridlist) - 1) {
2920             $last = true;
2921         }
2922         $user = $DB->get_record('user', array('id' => $userid));
2923         if ($user) {
2924             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2925             $usersummary = new assign_user_summary($user,
2926                                                    $this->get_course()->id,
2927                                                    $viewfullnames,
2928                                                    $this->is_blind_marking(),
2929                                                    $this->get_uniqueid_for_user($user->id),
2930                                                    get_extra_user_fields($this->get_context()),
2931                                                    !$this->is_active_user($userid));
2932             $o .= $this->get_renderer()->render($usersummary);
2933         }
2934         $submission = $this->get_user_submission($userid, false, $attemptnumber);
2935         $submissiongroup = null;
2936         $teamsubmission = null;
2937         $notsubmitted = array();
2938         if ($instance->teamsubmission) {
2939             $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2940             $submissiongroup = $this->get_submission_group($userid);
2941             $groupid = 0;
2942             if ($submissiongroup) {
2943                 $groupid = $submissiongroup->id;
2944             }
2945             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2947         }
2949         // Get the requested grade.
2950         $grade = $this->get_user_grade($userid, false, $attemptnumber);
2951         $flags = $this->get_user_flags($userid, false);
2952         if ($this->can_view_submission($userid)) {
2953             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2954             $extensionduedate = null;
2955             if ($flags) {
2956                 $extensionduedate = $flags->extensionduedate;
2957             }
2958             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2959             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2961             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2962                                                              $instance->alwaysshowdescription,
2963                                                              $submission,
2964                                                              $instance->teamsubmission,
2965                                                              $teamsubmission,
2966                                                              $submissiongroup,
2967                                                              $notsubmitted,
2968                                                              $this->is_any_submission_plugin_enabled(),
2969                                                              $gradelocked,
2970                                                              $this->is_graded($userid),
2971                                                              $instance->duedate,
2972                                                              $instance->cutoffdate,
2973                                                              $this->get_submission_plugins(),
2974                                                              $this->get_return_action(),
2975                                                              $this->get_return_params(),
2976                                                              $this->get_course_module()->id,
2977                                                              $this->get_course()->id,
2978                                                              assign_submission_status::GRADER_VIEW,
2979                                                              $showedit,
2980                                                              false,
2981                                                              $viewfullnames,
2982                                                              $extensionduedate,
2983                                                              $this->get_context(),
2984                                                              $this->is_blind_marking(),
2985                                                              '',
2986                                                              $instance->attemptreopenmethod,
2987                                                              $instance->maxattempts);
2988             $o .= $this->get_renderer()->render($submissionstatus);
2989         }
2991         if ($grade) {
2992             $data = new stdClass();
2993             if ($grade->grade !== null && $grade->grade >= 0) {
2994                 $data->grade = format_float($grade->grade, 2);
2995             }
2996             if (!empty($flags->workflowstate)) {
2997                 $data->workflowstate = $flags->workflowstate;
2998             }
2999             if (!empty($flags->allocatedmarker)) {
3000                 $data->allocatedmarker = $flags->allocatedmarker;
3001             }
3002         } else {
3003             $data = new stdClass();
3004             $data->grade = '';
3005         }
3006         // Warning if required.
3007         $allsubmissions = $this->get_all_submissions($userid);
3009         if ($attemptnumber != -1) {
3010             $params = array('attemptnumber'=>$attemptnumber + 1,
3011                             'totalattempts'=>count($allsubmissions));
3012             $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
3013             $o .= $this->get_renderer()->notification($message);
3014         }
3016         // Now show the grading form.
3017         if (!$mform) {
3018             $pagination = array('rownum'=>$rownum,
3019                                 'useridlistid'=>$useridlistid,
3020                                 'last'=>$last,
3021                                 'userid'=>optional_param('userid', 0, PARAM_INT),
3022                                 'attemptnumber'=>$attemptnumber);
3023             $formparams = array($this, $data, $pagination);
3024             $mform = new mod_assign_grade_form(null,
3025                                                $formparams,
3026                                                'post',
3027                                                '',
3028                                                array('class'=>'gradeform'));
3029         }
3030         $o .= $this->get_renderer()->heading(get_string('grade'), 3);
3031         $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
3033         if (count($allsubmissions) > 1 && $attemptnumber == -1) {
3034             $allgrades = $this->get_all_grades($userid);
3035             $history = new assign_attempt_history($allsubmissions,
3036                                                   $allgrades,
3037                                                   $this->get_submission_plugins(),
3038                                                   $this->get_feedback_plugins(),
3039                                                   $this->get_course_module()->id,
3040                                                   $this->get_return_action(),
3041                                                   $this->get_return_params(),
3042                                                   true,
3043                                                   $useridlistid,
3044                                                   $rownum);
3046             $o .= $this->get_renderer()->render($history);
3047         }
3049         \mod_assign\event\grading_form_viewed::create_from_user($this, $user)->trigger();
3051         $o .= $this->view_footer();
3052         return $o;
3053     }
3055     /**
3056      * Show a confirmation page to make sure they want to release student identities.
3057      *
3058      * @return string
3059      */
3060     protected function view_reveal_identities_confirm() {
3061         require_capability('mod/assign:revealidentities', $this->get_context());
3063         $o = '';
3064         $header = new assign_header($this->get_instance(),
3065                                     $this->get_context(),
3066                                     false,
3067                                     $this->get_course_module()->id);
3068         $o .= $this->get_renderer()->render($header);
3070         $urlparams = array('id'=>$this->get_course_module()->id,
3071                            'action'=>'revealidentitiesconfirm',
3072                            'sesskey'=>sesskey());
3073         $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
3075         $urlparams = array('id'=>$this->get_course_module()->id,
3076                            'action'=>'grading');
3077         $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
3079         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
3080                                              $confirmurl,
3081                                              $cancelurl);
3082         $o .= $this->view_footer();
3084         \mod_assign\event\reveal_identities_confirmation_page_viewed::create_from_assign($this)->trigger();
3086         return $o;
3087     }
3089     /**
3090      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
3091      *
3092      * @return string
3093      */
3094     protected function view_return_links() {
3095         $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
3096         $returnparams = optional_param('returnparams', '', PARAM_TEXT);
3098         $params = array();
3099         $returnparams = str_replace('&amp;', '&', $returnparams);
3100         parse_str($returnparams, $params);
3101         $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
3102         $params = array_merge($newparams, $params);
3104         $url = new moodle_url('/mod/assign/view.php', $params);
3105         return $this->get_renderer()->single_button($url, get_string('back'), 'get');
3106     }
3108     /**
3109      * View the grading table of all submissions for this assignment.
3110      *
3111      * @return string
3112      */
3113     protected function view_grading_table() {
3114         global $USER, $CFG;
3116         // Include grading options form.
3117         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
3118         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
3119         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3120         $o = '';
3121         $cmid = $this->get_course_module()->id;
3123         $links = array();
3124         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
3125                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
3126             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
3127             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
3128         }
3129         if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
3130             $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
3131             $links[$downloadurl] = get_string('downloadall', 'assign');
3132         }
3133         if ($this->is_blind_marking() &&
3134                 has_capability('mod/assign:revealidentities', $this->get_context())) {
3135             $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
3136             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
3137         }
3138         foreach ($this->get_feedback_plugins() as $plugin) {
3139             if ($plugin->is_enabled() && $plugin->is_visible()) {
3140                 foreach ($plugin->get_grading_actions() as $action => $description) {
3141                     $url = '/mod/assign/view.php' .
3142                            '?id=' .  $cmid .
3143                            '&plugin=' . $plugin->get_type() .
3144                            '&pluginsubtype=assignfeedback' .
3145                            '&action=viewpluginpage&pluginaction=' . $action;
3146                     $links[$url] = $description;
3147                 }
3148             }
3149         }
3151         // Sort links alphabetically based on the link description.
3152         core_collator::asort($links);
3154         $gradingactions = new url_select($links);
3155         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
3157         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3159         $perpage = (int) get_user_preferences('assign_perpage', 10);
3160         $filter = get_user_preferences('assign_filter', '');
3161         $markerfilter = get_user_preferences('assign_markerfilter', '');
3162         $workflowfilter = get_user_preferences('assign_workflowfilter', '');
3163         $controller = $gradingmanager->get_active_controller();
3164         $showquickgrading = empty($controller) && $this->can_grade();
3165         $quickgrading = get_user_preferences('assign_quickgrading', false);
3166         $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
3168         $markingallocation = $this->get_instance()->markingworkflow &&
3169             $this->get_instance()->markingallocation &&
3170             has_capability('mod/assign:manageallocations', $this->context);
3171         // Get markers to use in drop lists.
3172         $markingallocationoptions = array();
3173         if ($markingallocation) {
3174             $markers = get_users_by_capability($this->context, 'mod/assign:grade');
3175             $markingallocationoptions[''] = get_string('filternone', 'assign');
3176             $markingallocationoptions[ASSIGN_MARKER_FILTER_NO_MARKER] = get_string('markerfilternomarker', 'assign');
3177             foreach ($markers as $marker) {
3178                 $markingallocationoptions[$marker->id] = fullname($marker);
3179             }
3180         }
3182         $markingworkflow = $this->get_instance()->markingworkflow;
3183         // Get marking states to show in form.
3184         $markingworkflowoptions = array();
3185         if ($markingworkflow) {
3186             $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
3187             $markingworkflowoptions[''] = get_string('filternone', 'assign');
3188             $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
3189             $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
3190         }
3192         // Print options for changing the filter and changing the number of results per page.
3193         $gradingoptionsformparams = array('cm'=>$cmid,
3194                                           'contextid'=>$this->context->id,
3195                                           'userid'=>$USER->id,
3196                                           'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
3197                                           'showquickgrading'=>$showquickgrading,
3198                                           'quickgrading'=>$quickgrading,
3199                                           'markingworkflowopt'=>$markingworkflowoptions,
3200                                           'markingallocationopt'=>$markingallocationoptions,
3201                                           'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
3202                                           'showonlyactiveenrol'=>$this->show_only_active_users());
3204         $classoptions = array('class'=>'gradingoptionsform');
3205         $gradingoptionsform = new mod_assign_grading_options_form(null,
3206                                                                   $gradingoptionsformparams,
3207                                                                   'post',
3208                                                                   '',
3209                                                                   $classoptions);
3211         $batchformparams = array('cm'=>$cmid,
3212                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3213                                  'duedate'=>$this->get_instance()->duedate,
3214                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3215                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3216                                  'context'=>$this->get_context(),
3217                                  'markingworkflow'=>$markingworkflow,
3218                                  'markingallocation'=>$markingallocation);
3219         $classoptions = array('class'=>'gradingbatchoperationsform');
3221         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
3222                                                                                    $batchformparams,
3223                                                                                    'post',
3224                                                                                    '',
3225                                                                                    $classoptions);
3227         $gradingoptionsdata = new stdClass();
3228         $gradingoptionsdata->perpage = $perpage;
3229         $gradingoptionsdata->filter = $filter;
3230         $gradingoptionsdata->markerfilter = $markerfilter;
3231         $gradingoptionsdata->workflowfilter = $workflowfilter;
3232         $gradingoptionsform->set_data($gradingoptionsdata);
3234         $actionformtext = $this->get_renderer()->render($gradingactions);
3235         $header = new assign_header($this->get_instance(),
3236                                     $this->get_context(),
3237                                     false,
3238                                     $this->get_course_module()->id,
3239                                     get_string('grading', 'assign'),
3240                                     $actionformtext);
3241         $o .= $this->get_renderer()->render($header);
3243         $currenturl = $CFG->wwwroot .
3244                       '/mod/assign/view.php?id=' .
3245                       $this->get_course_module()->id .
3246                       '&action=grading';
3248         $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3250         // Plagiarism update status apearring in the grading book.
3251         if (!empty($CFG->enableplagiarism)) {
3252             require_once($CFG->libdir . '/plagiarismlib.php');
3253             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
3254         }
3256         // Load and print the table of submissions.
3257         if ($showquickgrading && $quickgrading) {
3258             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3259             $table = $this->get_renderer()->render($gradingtable);
3260             $page = optional_param('page', null, PARAM_INT);
3261             $quickformparams = array('cm'=>$this->get_course_module()->id,
3262                                      'gradingtable'=>$table,
3263                                      'sendstudentnotifications' => $this->get_instance()->sendstudentnotifications,
3264                                      'page' => $page);
3265             $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3267             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3268         } else {
3269             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3270             $o .= $this->get_renderer()->render($gradingtable);
3271         }
3273         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3274         $users = array_keys($this->list_participants($currentgroup, true));
3275         if (count($users) != 0 && $this->can_grade()) {
3276             // If no enrolled user in a course then don't display the batch operations feature.
3277             $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3278             $o .= $this->get_renderer()->render($assignform);
3279         }
3280         $assignform = new assign_form('gradingoptionsform',
3281                                       $gradingoptionsform,
3282                                       'M.mod_assign.init_grading_options');
3283         $o .= $this->get_renderer()->render($assignform);
3284         return $o;
3285     }
3287     /**
3288      * View entire grading page.
3289      *
3290      * @return string
3291      */
3292     protected function view_grading_page() {
3293         global $CFG;
3295         $o = '';
3296         // Need submit permission to submit an assignment.
3297         $this->require_view_grades();
3298         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3300         // Only load this if it is.
3302         $o .= $this->view_grading_table();
3304         $o .= $this->view_footer();
3306         \mod_assign\event\grading_table_viewed::create_from_assign($this)->trigger();
3308         return $o;
3309     }
3311     /**
3312      * Capture the output of the plagiarism plugins disclosures and return it as a string.
3313      *
3314      * @return string
3315      */
3316     protected function plagiarism_print_disclosure() {
3317         global $CFG;
3318         $o = '';
3320         if (!empty($CFG->enableplagiarism)) {
3321             require_once($CFG->libdir . '/plagiarismlib.php');
3323             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3324         }
3326         return $o;
3327     }
3329     /**
3330      * Message for students when assignment submissions have been closed.
3331      *
3332      * @param string $title The page title
3333      * @param array $notices The array of notices to show.
3334      * @return string
3335      */
3336     protected function view_notices($title, $notices) {
3337         global $CFG;
3339         $o = '';
3341         $header = new assign_header($this->get_instance(),
3342                                     $this->get_context(),
3343                                     $this->show_intro(),
3344                                     $this->get_course_module()->id,
3345                                     $title);
3346         $o .= $this->get_renderer()->render($header);
3348         foreach ($notices as $notice) {
3349             $o .= $this->get_renderer()->notification($notice);
3350         }
3352         $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id, 'action'=>'view'));
3353         $o .= $this->get_renderer()->continue_button($url);
3355         $o .= $this->view_footer();
3357         return $o;
3358     }
3360     /**
3361      * Get the name for a user - hiding their real name if blind marking is on.
3362      *
3363      * @param stdClass $user The user record as required by fullname()
3364      * @return string The name.
3365      */
3366     public function fullname($user) {
3367         if ($this->is_blind_marking()) {
3368             $hasviewblind = has_capability('mod/assign:viewblinddetails', $this->get_context());
3369             if ($hasviewblind) {
3370                 return fullname($user);
3371             } else {
3372                 $uniqueid = $this->get_uniqueid_for_user($user->id);
3373                 return get_string('participant', 'assign') . ' ' . $uniqueid;
3374             }
3375         } else {
3376             return fullname($user);
3377         }
3378     }
3380     /**
3381      * View edit submissions page.
3382      *
3383      * @param moodleform $mform
3384      * @param array $notices A list of notices to display at the top of the
3385      *                       edit submission form (e.g. from plugins).
3386      * @return string The page output.
3387      */
3388     protected function view_edit_submission_page($mform, $notices) {
3389         global $CFG, $USER, $DB;
3391         $o = '';
3392         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
3393         // Need submit permission to submit an assignment.
3394         $userid = optional_param('userid', $USER->id, PARAM_INT);
3395         $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
3396         if ($userid == $USER->id) {
3397             // User is editing their own submission.
3398             require_capability('mod/assign:submit', $this->context);
3399             $title = get_string('editsubmission', 'assign');
3400         } else {
3401             // User is editing another user's submission.
3402             if (!$this->can_edit_submission($userid, $USER->id)) {
3403                 print_error('nopermission');
3404             }
3406             $name = $this->fullname($user);
3407             $title = get_string('editsubmissionother', 'assign', $name);
3408         }
3410         if (!$this->submissions_open($userid)) {
3411             $message = array(get_string('submissionsclosed', 'assign'));
3412             return $this->view_notices($title, $message);
3413         }
3415         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3416                                                       $this->get_context(),
3417                                                       $this->show_intro(),
3418                                                       $this->get_course_module()->id,
3419                                                       $title));
3420         if ($userid == $USER->id) {
3421             // We only show this if it their submission.
3422             $o .= $this->plagiarism_print_disclosure();
3423         }
3424         $data = new stdClass();
3425         $data->userid = $userid;
3426         if (!$mform) {
3427             $mform = new mod_assign_submission_form(null, array($this, $data));
3428         }
3430         foreach ($notices as $notice) {
3431             $o .= $this->get_renderer()->notification($notice);
3432         }
3434         $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
3436         $o .= $this->view_footer();
3438         \mod_assign\event\submission_form_viewed::create_from_user($this, $user)->trigger();
3440         return $o;
3441     }
3443     /**
3444      * See if this assignment has a grade yet.
3445      *
3446      * @param int $userid
3447      * @return bool
3448      */
3449     protected function is_graded($userid) {
3450         $grade = $this->get_user_grade($userid, false);
3451         if ($grade) {
3452             return ($grade->grade !== null && $grade->grade >= 0);
3453         }
3454         return false;
3455     }
3457     /**
3458      * Perform an access check to see if the current $USER can view this group submission.
3459      *
3460      * @param int $groupid
3461      * @return bool
3462      */
3463     public function can_view_group_submission($groupid) {
3464         global $USER;
3466         if (has_capability('mod/assign:grade', $this->context)) {
3467             return true;
3468         }
3469         if (!is_enrolled($this->get_course_context(), $USER->id)) {
3470             return false;
3471         }
3472         $members = $this->get_submission_group_members($groupid, true);
3473         foreach ($members as $member) {
3474             if ($member->id == $USER->id) {
3475                 return true;
3476             }
3477         }
3478         return false;
3479     }
3481     /**
3482      * Perform an access check to see if the current $USER can view this users submission.
3483      *
3484      * @param int $userid
3485      * @return bool
3486      */
3487     public function can_view_submission($userid) {
3488         global $USER;
3490         if (!$this->is_active_user($userid) && !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
3491             return false;
3492         }
3493         if (has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
3494             return true;
3495         }
3496         if (!is_enrolled($this->get_course_context(), $userid)) {
3497             return false;
3498         }
3499         if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
3500             return true;
3501         }
3502         return false;
3503     }
3505     /**
3506      * Allows the plugin to show a batch grading operation page.
3507      *
3508      * @param moodleform $mform
3509      * @return none
3510      */
3511     protected function view_plugin_grading_batch_operation($mform) {
3512         require_capability('mod/assign:grade', $this->context);
3513         $prefix = 'plugingradingbatchoperation_';
3515         if ($data = $mform->get_data()) {
3516             $tail = substr($data->operation, strlen($prefix));
3517             list($plugintype, $action) = explode('_', $tail, 2);
3519             $plugin = $this->get_feedback_plugin_by_type($plugintype);
3520             if ($plugin) {
3521                 $users = $data->selectedusers;
3522                 $userlist = explode(',', $users);
3523                 echo $plugin->grading_batch_operation($action, $userlist);
3524                 return;
3525             }
3526         }
3527         print_error('invalidformdata', '');
3528     }
3530     /**
3531      * Ask the user to confirm they want to perform this batch operation
3532      *
3533      * @param moodleform $mform Set to a grading batch operations form
3534      * @return string - the page to view after processing these actions
3535      */
3536     protected function process_grading_batch_operation(& $mform) {
3537         global $CFG;
3538         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3539         require_sesskey();
3541         $markingallocation = $this->get_instance()->markingworkflow &&
3542             $this->get_instance()->markingallocation &&
3543             has_capability('mod/assign:manageallocations', $this->context);
3545         $batchformparams = array('cm'=>$this->get_course_module()->id,
3546                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3547                                  'duedate'=>$this->get_instance()->duedate,
3548                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3549                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3550                                  'context'=>$this->get_context(),
3551                                  'markingworkflow'=>$this->get_instance()->markingworkflow,
3552                                  'markingallocation'=>$markingallocation);
3553         $formclasses = array('class'=>'gradingbatchoperationsform');
3554         $mform = new mod_assign_grading_batch_operations_form(null,
3555                                                               $batchformparams,
3556                                                               'post',
3557                                                               '',
3558                                                               $formclasses);
3560         if ($data = $mform->get_data()) {
3561             // Get the list of users.
3562             $users = $data->selectedusers;
3563             $userlist = explode(',', $users);
3565             $prefix = 'plugingradingbatchoperation_';
3567             if ($data->operation == 'grantextension') {
3568                 // Reset the form so the grant extension page will create the extension form.
3569                 $mform = null;
3570                 return 'grantextension';
3571             } else if ($data->operation == 'setmarkingworkflowstate') {
3572                 return 'viewbatchsetmarkingworkflowstate';
3573             } else if ($data->operation == 'setmarkingallocation') {
3574                 return 'viewbatchmarkingallocation';
3575             } else if (strpos($data->operation, $prefix) === 0) {
3576                 $tail = substr($data->operation, strlen($prefix));
3577                 list($plugintype, $action) = explode('_', $tail, 2);
3579                 $plugin = $this->get_feedback_plugin_by_type($plugintype);
3580                 if ($plugin) {
3581                     return 'plugingradingbatchoperation';
3582                 }
3583             }
3585             foreach ($userlist as $userid) {
3586                 if ($data->operation == 'lock') {
3587                     $this->process_lock_submission($userid);
3588                 } else if ($data->operation == 'unlock') {
3589                     $this->process_unlock_submission($userid);
3590                 } else if ($data->operation == 'reverttodraft') {
3591                     $this->process_revert_to_draft($userid);
3592                 } else if ($data->operation == 'addattempt') {
3593                     if (!$this->get_instance()->teamsubmission) {
3594                         $this->process_add_attempt($userid);
3595                     }
3596                 }
3597             }
3598             if ($this->get_instance()->teamsubmission && $data->operation == 'addattempt') {
3599                 // This needs to be handled separately so that each team submission is only re-opened one time.
3600                 $this->process_add_attempt_group($userlist);
3601             }
3602         }
3604         return 'grading';
3605     }
3607     /**
3608      * Shows a form that allows the workflow state for selected submissions to be changed.
3609      *
3610      * @param moodleform $mform Set to a grading batch operations form
3611      * @return string - the page to view after processing these actions
3612      */
3613     protected function view_batch_set_workflow_state($mform) {
3614         global $CFG, $DB;
3616         require_once($CFG->dirroot . '/mod/assign/batchsetmarkingworkflowstateform.php');
3618         $o = '';
3620         $submitteddata = $mform->get_data();
3621         $users = $submitteddata->selectedusers;
3622         $userlist = explode(',', $users);
3624         $formdata = array('id' => $this->get_course_module()->id,
3625                           'selectedusers' => $users);
3627         $usershtml = '';
3629         $usercount = 0;
3630         $extrauserfields = get_extra_user_fields($this->get_context());
3631         foreach ($userlist as $userid) {
3632             if ($usercount >= 5) {
3633                 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
3634                 break;
3635             }
3636             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
3638             $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
3639                                                                 $this->get_course()->id,
3640                                                                 has_capability('moodle/site:viewfullnames',
3641                                                                 $this->get_course_context()),
3642                                                                 $this->is_blind_marking(),
3643                                                                 $this->get_uniqueid_for_user($user->id),
3644                                                                 $extrauserfields,
3645                                                                 !$this->is_active_user($userid)));
3646             $usercount += 1;
3647         }
3649         $formparams = array(
3650             'userscount' => count($userlist),
3651             'usershtml' => $usershtml,
3652             'markingworkflowstates' => $this->get_marking_workflow_states_for_current_user()
3653         );
3655         $mform = new mod_assign_batch_set_marking_workflow_state_form(null, $formparams);
3656         $mform->set_data($formdata);    // Initialises the hidden elements.
3657         $o .= $this->get_renderer()->header();
3658         $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
3659         $o .= $this->view_footer();
3661         \mod_assign\event\batch_set_workflow_state_viewed::create_from_assign($this)->trigger();
3663         return $o;
3664     }
3666     /**
3667      * Shows a form that allows the allocated marker for selected submissions to be changed.
3668      *
3669      * @param moodleform $mform Set to a grading batch operations form
3670      * @return string - the page to view after processing these actions
3671      */
3672     public function view_batch_markingallocation($mform) {
3673         global $CFG, $DB;
3675         require_once($CFG->dirroot . '/mod/assign/batchsetallocatedmarkerform.php');
3677         $o = '';
3679         $submitteddata = $mform->get_data();
3680         $users = $submitteddata->selectedusers;
3681         $userlist = explode(',', $users);
3683         $formdata = array('id' => $this->get_course_module()->id,
3684                           'selectedusers' => $users);
3686         $usershtml = '';
3688         $usercount = 0;
3689         $extrauserfields = get_extra_user_fields($this->get_context());
3690         foreach ($userlist as $userid) {
3691             if ($usercount >= 5) {
3692                 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
3693                 break;
3694             }
3695             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
3697             $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
3698                 $this->get_course()->id,
3699                 has_capability('moodle/site:viewfullnames',
3700                 $this->get_course_context()),
3701                 $this->is_blind_marking(),
3702                 $this->get_uniqueid_for_user($user->id),
3703                 $extrauserfields,
3704                 !$this->is_active_user($userid)));
3705             $usercount += 1;
3706         }
3708         $formparams = array(
3709             'userscount' => count($userlist),
3710             'usershtml' => $usershtml,
3711         );
3713         $markers = get_users_by_capability($this->get_context(), 'mod/assign:grade');
3714         $markerlist = array();
3715         foreach ($markers as $marker) {
3716             $markerlist[$marker->id] = fullname($marker);
3717         }
3719         $formparams['markers'] = $markerlist;
3721         $mform = new mod_assign_batch_set_allocatedmarker_form(null, $formparams);
3722         $mform->set_data($formdata);    // Initialises the hidden elements.
3723         $o .= $this->get_renderer()->header();
3724         $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
3725         $o .= $this->view_footer();
3727         \mod_assign\event\batch_set_marker_allocation_viewed::create_from_assign($this)->trigger();
3729         return $o;
3730     }
3732     /**
3733      * Ask the user to confirm they want to submit their work for grading.
3734      *
3735      * @param moodleform $mform - null unless form validation has failed
3736      * @return string
3737      */
3738     protected function check_submit_for_grading($mform) {
3739         global $USER, $CFG;
3741         require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
3743         // Check that all of the submission plugins are ready for this submission.
3744         $notifications = array();
3745         $submission = $this->get_user_submission($USER->id, false);
3746         $plugins = $this->get_submission_plugins();
3747         foreach ($plugins as $plugin) {
3748             if ($plugin->is_enabled() && $plugin->is_visible()) {
3749                 $check = $plugin->precheck_submission($submission);
3750                 if ($check !== true) {
3751                     $notifications[] = $check;
3752                 }
3753             }
3754         }
3756         $data = new stdClass();
3757         $adminconfig = $this->get_admin_config();
3758         $requiresubmissionstatement = $this->get_instance()->requiresubmissionstatement &&
3759                                        !empty($adminconfig->submissionstatement);
3761         $submissionstatement = '';
3762         if (!empty($adminconfig->submissionstatement)) {
3763             // Format the submission statement before its sent. We turn off para because this is going within
3764             // a form element.
3765             $options = array(
3766                 'context' => $this->get_context(),
3767                 'para' => false
3768             );
3769             $submissionstatement = format_text($adminconfig->submissionstatement, FORMAT_MOODLE, $options);
3770         }
3772         if ($mform == null) {
3773             $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
3774                                                                         $submissionstatement,
3775                                                                         $this->get_course_module()->id,
3776                                                                         $data));
3777         }
3778         $o = '';
3779         $o .= $this->get_renderer()->header();
3780         $submitforgradingpage = new assign_submit_for_grading_page($notifications,