MDL-37153 - assign: Obey grade display settings in submission status
[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_REOPENED', 'reopened');
31 define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft');
32 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted');
34 // Search filters for grading page.
35 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
36 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
37 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
39 // Reopen attempt methods.
40 define('ASSIGN_ATTEMPT_REOPEN_METHOD_NONE', 'none');
41 define('ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL', 'manual');
42 define('ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS', 'untilpass');
44 // Special value means allow unlimited attempts.
45 define('ASSIGN_UNLIMITED_ATTEMPTS', -1);
47 // Marking workflow states.
48 define('ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED', 'notmarked');
49 define('ASSIGN_MARKING_WORKFLOW_STATE_INMARKING', 'inmarking');
50 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW', 'readyforreview');
51 define('ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW', 'inreview');
52 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE', 'readyforrelease');
53 define('ASSIGN_MARKING_WORKFLOW_STATE_RELEASED', 'released');
55 require_once($CFG->libdir . '/accesslib.php');
56 require_once($CFG->libdir . '/formslib.php');
57 require_once($CFG->dirroot . '/repository/lib.php');
58 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
59 require_once($CFG->libdir . '/gradelib.php');
60 require_once($CFG->dirroot . '/grade/grading/lib.php');
61 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
62 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
63 require_once($CFG->dirroot . '/mod/assign/renderable.php');
64 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
65 require_once($CFG->libdir . '/eventslib.php');
66 require_once($CFG->libdir . '/portfolio/caller.php');
68 /**
69  * Standard base class for mod_assign (assignment types).
70  *
71  * @package   mod_assign
72  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
73  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
74  */
75 class assign {
77     /** @var stdClass the assignment record that contains the global settings for this assign instance */
78     private $instance;
80     /** @var stdClass the grade_item record for this assign instance's primary grade item. */
81     private $gradeitem;
83     /** @var context the context of the course module for this assign instance
84      *               (or just the course if we are creating a new one)
85      */
86     private $context;
88     /** @var stdClass the course this assign instance belongs to */
89     private $course;
91     /** @var stdClass the admin config for all assign instances  */
92     private $adminconfig;
94     /** @var assign_renderer the custom renderer for this module */
95     private $output;
97     /** @var stdClass the course module for this assign instance */
98     private $coursemodule;
100     /** @var array cache for things like the coursemodule name or the scale menu -
101      *             only lives for a single request.
102      */
103     private $cache;
105     /** @var array list of the installed submission plugins */
106     private $submissionplugins;
108     /** @var array list of the installed feedback plugins */
109     private $feedbackplugins;
111     /** @var string action to be used to return to this page
112      *              (without repeating any form submissions etc).
113      */
114     private $returnaction = 'view';
116     /** @var array params to be used to return to this page */
117     private $returnparams = array();
119     /** @var string modulename prevents excessive calls to get_string */
120     private static $modulename = null;
122     /** @var string modulenameplural prevents excessive calls to get_string */
123     private static $modulenameplural = null;
125     /** @var array of marking workflow states for the current user */
126     private $markingworkflowstates = null;
128     /** @var bool whether to exclude users with inactive enrolment */
129     private $showonlyactiveenrol = null;
131     /** @var array list of suspended user IDs in form of ([id1] => id1) */
132     public $susers = null;
134     /**
135      * Constructor for the base assign class.
136      *
137      * @param mixed $coursemodulecontext context|null the course module context
138      *                                   (or the course context if the coursemodule has not been
139      *                                   created yet).
140      * @param mixed $coursemodule the current course module if it was already loaded,
141      *                            otherwise this class will load one from the context as required.
142      * @param mixed $course the current course  if it was already loaded,
143      *                      otherwise this class will load one from the context as required.
144      */
145     public function __construct($coursemodulecontext, $coursemodule, $course) {
146         $this->context = $coursemodulecontext;
147         $this->coursemodule = $coursemodule;
148         $this->course = $course;
150         // Temporary cache only lives for a single request - used to reduce db lookups.
151         $this->cache = array();
153         $this->submissionplugins = $this->load_plugins('assignsubmission');
154         $this->feedbackplugins = $this->load_plugins('assignfeedback');
155     }
157     /**
158      * Set the action and parameters that can be used to return to the current page.
159      *
160      * @param string $action The action for the current page
161      * @param array $params An array of name value pairs which form the parameters
162      *                      to return to the current page.
163      * @return void
164      */
165     public function register_return_link($action, $params) {
166         global $PAGE;
167         $params['action'] = $action;
168         $currenturl = $PAGE->url;
170         $currenturl->params($params);
171         $PAGE->set_url($currenturl);
172     }
174     /**
175      * Return an action that can be used to get back to the current page.
176      *
177      * @return string action
178      */
179     public function get_return_action() {
180         global $PAGE;
182         $params = $PAGE->url->params();
184         if (!empty($params['action'])) {
185             return $params['action'];
186         }
187         return '';
188     }
190     /**
191      * Based on the current assignment settings should we display the intro.
192      *
193      * @return bool showintro
194      */
195     protected function show_intro() {
196         if ($this->get_instance()->alwaysshowdescription ||
197                 time() > $this->get_instance()->allowsubmissionsfromdate) {
198             return true;
199         }
200         return false;
201     }
203     /**
204      * Return a list of parameters that can be used to get back to the current page.
205      *
206      * @return array params
207      */
208     public function get_return_params() {
209         global $PAGE;
211         $params = $PAGE->url->params();
212         unset($params['id']);
213         unset($params['action']);
214         return $params;
215     }
217     /**
218      * Set the submitted form data.
219      *
220      * @param stdClass $data The form data (instance)
221      */
222     public function set_instance(stdClass $data) {
223         $this->instance = $data;
224     }
226     /**
227      * Set the context.
228      *
229      * @param context $context The new context
230      */
231     public function set_context(context $context) {
232         $this->context = $context;
233     }
235     /**
236      * Set the course data.
237      *
238      * @param stdClass $course The course data
239      */
240     public function set_course(stdClass $course) {
241         $this->course = $course;
242     }
244     /**
245      * Get list of feedback plugins installed.
246      *
247      * @return array
248      */
249     public function get_feedback_plugins() {
250         return $this->feedbackplugins;
251     }
253     /**
254      * Get list of submission plugins installed.
255      *
256      * @return array
257      */
258     public function get_submission_plugins() {
259         return $this->submissionplugins;
260     }
262     /**
263      * Is blind marking enabled and reveal identities not set yet?
264      *
265      * @return bool
266      */
267     public function is_blind_marking() {
268         return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
269     }
271     /**
272      * Does an assignment have submission(s) or grade(s) already?
273      *
274      * @return bool
275      */
276     public function has_submissions_or_grades() {
277         $allgrades = $this->count_grades();
278         $allsubmissions = $this->count_submissions();
279         if (($allgrades == 0) && ($allsubmissions == 0)) {
280             return false;
281         }
282         return true;
283     }
285     /**
286      * Get a specific submission plugin by its type.
287      *
288      * @param string $subtype assignsubmission | assignfeedback
289      * @param string $type
290      * @return mixed assign_plugin|null
291      */
292     public function get_plugin_by_type($subtype, $type) {
293         $shortsubtype = substr($subtype, strlen('assign'));
294         $name = $shortsubtype . 'plugins';
295         if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
296             return null;
297         }
298         $pluginlist = $this->$name;
299         foreach ($pluginlist as $plugin) {
300             if ($plugin->get_type() == $type) {
301                 return $plugin;
302             }
303         }
304         return null;
305     }
307     /**
308      * Get a feedback plugin by type.
309      *
310      * @param string $type - The type of plugin e.g comments
311      * @return mixed assign_feedback_plugin|null
312      */
313     public function get_feedback_plugin_by_type($type) {
314         return $this->get_plugin_by_type('assignfeedback', $type);
315     }
317     /**
318      * Get a submission plugin by type.
319      *
320      * @param string $type - The type of plugin e.g comments
321      * @return mixed assign_submission_plugin|null
322      */
323     public function get_submission_plugin_by_type($type) {
324         return $this->get_plugin_by_type('assignsubmission', $type);
325     }
327     /**
328      * Load the plugins from the sub folders under subtype.
329      *
330      * @param string $subtype - either submission or feedback
331      * @return array - The sorted list of plugins
332      */
333     protected function load_plugins($subtype) {
334         global $CFG;
335         $result = array();
337         $names = core_component::get_plugin_list($subtype);
339         foreach ($names as $name => $path) {
340             if (file_exists($path . '/locallib.php')) {
341                 require_once($path . '/locallib.php');
343                 $shortsubtype = substr($subtype, strlen('assign'));
344                 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
346                 $plugin = new $pluginclass($this, $name);
348                 if ($plugin instanceof assign_plugin) {
349                     $idx = $plugin->get_sort_order();
350                     while (array_key_exists($idx, $result)) {
351                         $idx +=1;
352                     }
353                     $result[$idx] = $plugin;
354                 }
355             }
356         }
357         ksort($result);
358         return $result;
359     }
361     /**
362      * Display the assignment, used by view.php
363      *
364      * The assignment is displayed differently depending on your role,
365      * the settings for the assignment and the status of the assignment.
366      *
367      * @param string $action The current action if any.
368      * @return string - The page output.
369      */
370     public function view($action='') {
372         $o = '';
373         $mform = null;
374         $notices = array();
375         $nextpageparams = array();
377         if (!empty($this->get_course_module()->id)) {
378             $nextpageparams['id'] = $this->get_course_module()->id;
379         }
381         // Handle form submissions first.
382         if ($action == 'savesubmission') {
383             $action = 'editsubmission';
384             if ($this->process_save_submission($mform, $notices)) {
385                 $action = 'redirect';
386                 $nextpageparams['action'] = 'view';
387             }
388         } else if ($action == 'editprevioussubmission') {
389             $action = 'editsubmission';
390             if ($this->process_copy_previous_attempt($notices)) {
391                 $action = 'redirect';
392                 $nextpageparams['action'] = 'editsubmission';
393             }
394         } else if ($action == 'lock') {
395             $this->process_lock_submission();
396             $action = 'redirect';
397             $nextpageparams['action'] = 'grading';
398         } else if ($action == 'addattempt') {
399             $this->process_add_attempt(required_param('userid', PARAM_INT));
400             $action = 'redirect';
401             $nextpageparams['action'] = 'grading';
402         } else if ($action == 'reverttodraft') {
403             $this->process_revert_to_draft();
404             $action = 'redirect';
405             $nextpageparams['action'] = 'grading';
406         } else if ($action == 'unlock') {
407             $this->process_unlock_submission();
408             $action = 'redirect';
409             $nextpageparams['action'] = 'grading';
410         } else if ($action == 'setbatchmarkingworkflowstate') {
411             $this->process_set_batch_marking_workflow_state();
412             $action = 'redirect';
413             $nextpageparams['action'] = 'grading';
414         } else if ($action == 'setbatchmarkingallocation') {
415             $this->process_set_batch_marking_allocation();
416             $action = 'redirect';
417             $nextpageparams['action'] = 'grading';
418         } else if ($action == 'confirmsubmit') {
419             $action = 'submit';
420             if ($this->process_submit_for_grading($mform)) {
421                 $action = 'redirect';
422                 $nextpageparams['action'] = 'view';
423             }
424         } else if ($action == 'gradingbatchoperation') {
425             $action = $this->process_grading_batch_operation($mform);
426             if ($action == 'grading') {
427                 $action = 'redirect';
428                 $nextpageparams['action'] = 'grading';
429             }
430         } else if ($action == 'submitgrade') {
431             if (optional_param('saveandshownext', null, PARAM_RAW)) {
432                 // Save and show next.
433                 $action = 'grade';
434                 if ($this->process_save_grade($mform)) {
435                     $action = 'redirect';
436                     $nextpageparams['action'] = 'grade';
437                     $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
438                     $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
439                 }
440             } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
441                 $action = 'redirect';
442                 $nextpageparams['action'] = 'grade';
443                 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
444                 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
445             } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
446                 $action = 'redirect';
447                 $nextpageparams['action'] = 'grade';
448                 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
449                 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
450             } else if (optional_param('savegrade', null, PARAM_RAW)) {
451                 // Save changes button.
452                 $action = 'grade';
453                 if ($this->process_save_grade($mform)) {
454                     $message = get_string('gradingchangessaved', 'assign');
455                     $action = 'savegradingresult';
456                 }
457             } else {
458                 // Cancel button.
459                 $action = 'redirect';
460                 $nextpageparams['action'] = 'grading';
461             }
462         } else if ($action == 'quickgrade') {
463             $message = $this->process_save_quick_grades();
464             $action = 'quickgradingresult';
465         } else if ($action == 'saveoptions') {
466             $this->process_save_grading_options();
467             $action = 'redirect';
468             $nextpageparams['action'] = 'grading';
469         } else if ($action == 'saveextension') {
470             $action = 'grantextension';
471             if ($this->process_save_extension($mform)) {
472                 $action = 'redirect';
473                 $nextpageparams['action'] = 'grading';
474             }
475         } else if ($action == 'revealidentitiesconfirm') {
476             $this->process_reveal_identities();
477             $action = 'redirect';
478             $nextpageparams['action'] = 'grading';
479         }
481         $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
482                               'useridlistid'=>optional_param('useridlistid', 0, PARAM_INT));
483         $this->register_return_link($action, $returnparams);
485         // Now show the right view page.
486         if ($action == 'redirect') {
487             $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
488             redirect($nextpageurl);
489             return;
490         } else if ($action == 'savegradingresult') {
491             $o .= $this->view_savegrading_result($message);
492         } else if ($action == 'quickgradingresult') {
493             $mform = null;
494             $o .= $this->view_quickgrading_result($message);
495         } else if ($action == 'grade') {
496             $o .= $this->view_single_grade_page($mform);
497         } else if ($action == 'viewpluginassignfeedback') {
498             $o .= $this->view_plugin_content('assignfeedback');
499         } else if ($action == 'viewpluginassignsubmission') {
500             $o .= $this->view_plugin_content('assignsubmission');
501         } else if ($action == 'editsubmission') {
502             $o .= $this->view_edit_submission_page($mform, $notices);
503         } else if ($action == 'grading') {
504             $o .= $this->view_grading_page();
505         } else if ($action == 'downloadall') {
506             $o .= $this->download_submissions();
507         } else if ($action == 'submit') {
508             $o .= $this->check_submit_for_grading($mform);
509         } else if ($action == 'grantextension') {
510             $o .= $this->view_grant_extension($mform);
511         } else if ($action == 'revealidentities') {
512             $o .= $this->view_reveal_identities_confirm($mform);
513         } else if ($action == 'plugingradingbatchoperation') {
514             $o .= $this->view_plugin_grading_batch_operation($mform);
515         } else if ($action == 'viewpluginpage') {
516              $o .= $this->view_plugin_page();
517         } else if ($action == 'viewcourseindex') {
518              $o .= $this->view_course_index();
519         } else if ($action == 'viewbatchsetmarkingworkflowstate') {
520              $o .= $this->view_batch_set_workflow_state($mform);
521         } else if ($action == 'viewbatchmarkingallocation') {
522             $o .= $this->view_batch_markingallocation($mform);
523         } else {
524             $o .= $this->view_submission_page();
525         }
527         return $o;
528     }
530     /**
531      * Add this instance to the database.
532      *
533      * @param stdClass $formdata The data submitted from the form
534      * @param bool $callplugins This is used to skip the plugin code
535      *             when upgrading an old assignment to a new one (the plugins get called manually)
536      * @return mixed false if an error occurs or the int id of the new instance
537      */
538     public function add_instance(stdClass $formdata, $callplugins) {
539         global $DB;
541         $err = '';
543         // Add the database record.
544         $update = new stdClass();
545         $update->name = $formdata->name;
546         $update->timemodified = time();
547         $update->timecreated = time();
548         $update->course = $formdata->course;
549         $update->courseid = $formdata->course;
550         $update->intro = $formdata->intro;
551         $update->introformat = $formdata->introformat;
552         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
553         $update->submissiondrafts = $formdata->submissiondrafts;
554         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
555         $update->sendnotifications = $formdata->sendnotifications;
556         $update->sendlatenotifications = $formdata->sendlatenotifications;
557         $update->duedate = $formdata->duedate;
558         $update->cutoffdate = $formdata->cutoffdate;
559         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
560         $update->grade = $formdata->grade;
561         $update->completionsubmit = !empty($formdata->completionsubmit);
562         $update->teamsubmission = $formdata->teamsubmission;
563         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
564         if (isset($formdata->teamsubmissiongroupingid)) {
565             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
566         }
567         $update->blindmarking = $formdata->blindmarking;
568         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
569         if (!empty($formdata->attemptreopenmethod)) {
570             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
571         }
572         if (!empty($formdata->maxattempts)) {
573             $update->maxattempts = $formdata->maxattempts;
574         }
575         $update->markingworkflow = $formdata->markingworkflow;
576         $update->markingallocation = $formdata->markingallocation;
578         $returnid = $DB->insert_record('assign', $update);
579         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
580         // Cache the course record.
581         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
583         if ($callplugins) {
584             // Call save_settings hook for submission plugins.
585             foreach ($this->submissionplugins as $plugin) {
586                 if (!$this->update_plugin_instance($plugin, $formdata)) {
587                     print_error($plugin->get_error());
588                     return false;
589                 }
590             }
591             foreach ($this->feedbackplugins as $plugin) {
592                 if (!$this->update_plugin_instance($plugin, $formdata)) {
593                     print_error($plugin->get_error());
594                     return false;
595                 }
596             }
598             // In the case of upgrades the coursemodule has not been set,
599             // so we need to wait before calling these two.
600             $this->update_calendar($formdata->coursemodule);
601             $this->update_gradebook(false, $formdata->coursemodule);
603         }
605         $update = new stdClass();
606         $update->id = $this->get_instance()->id;
607         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
608         $DB->update_record('assign', $update);
610         return $returnid;
611     }
613     /**
614      * Delete all grades from the gradebook for this assignment.
615      *
616      * @return bool
617      */
618     protected function delete_grades() {
619         global $CFG;
621         $result = grade_update('mod/assign',
622                                $this->get_course()->id,
623                                'mod',
624                                'assign',
625                                $this->get_instance()->id,
626                                0,
627                                null,
628                                array('deleted'=>1));
629         return $result == GRADE_UPDATE_OK;
630     }
632     /**
633      * Delete this instance from the database.
634      *
635      * @return bool false if an error occurs
636      */
637     public function delete_instance() {
638         global $DB;
639         $result = true;
641         foreach ($this->submissionplugins as $plugin) {
642             if (!$plugin->delete_instance()) {
643                 print_error($plugin->get_error());
644                 $result = false;
645             }
646         }
647         foreach ($this->feedbackplugins as $plugin) {
648             if (!$plugin->delete_instance()) {
649                 print_error($plugin->get_error());
650                 $result = false;
651             }
652         }
654         // Delete files associated with this assignment.
655         $fs = get_file_storage();
656         if (! $fs->delete_area_files($this->context->id) ) {
657             $result = false;
658         }
660         // Delete_records will throw an exception if it fails - so no need for error checking here.
661         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
662         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
663         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
665         // Delete items from the gradebook.
666         if (! $this->delete_grades()) {
667             $result = false;
668         }
670         // Delete the instance.
671         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
673         return $result;
674     }
676     /**
677      * Actual implementation of the reset course functionality, delete all the
678      * assignment submissions for course $data->courseid.
679      *
680      * @param stdClass $data the data submitted from the reset course.
681      * @return array status array
682      */
683     public function reset_userdata($data) {
684         global $CFG, $DB;
686         $componentstr = get_string('modulenameplural', 'assign');
687         $status = array();
689         $fs = get_file_storage();
690         if (!empty($data->reset_assign_submissions)) {
691             // Delete files associated with this assignment.
692             foreach ($this->submissionplugins as $plugin) {
693                 $fileareas = array();
694                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
695                 $fileareas = $plugin->get_file_areas();
696                 foreach ($fileareas as $filearea) {
697                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
698                 }
700                 if (!$plugin->delete_instance()) {
701                     $status[] = array('component'=>$componentstr,
702                                       'item'=>get_string('deleteallsubmissions', 'assign'),
703                                       'error'=>$plugin->get_error());
704                 }
705             }
707             foreach ($this->feedbackplugins as $plugin) {
708                 $fileareas = array();
709                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
710                 $fileareas = $plugin->get_file_areas();
711                 foreach ($fileareas as $filearea) {
712                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
713                 }
715                 if (!$plugin->delete_instance()) {
716                     $status[] = array('component'=>$componentstr,
717                                       'item'=>get_string('deleteallsubmissions', 'assign'),
718                                       'error'=>$plugin->get_error());
719                 }
720             }
722             $assignssql = 'SELECT a.id
723                              FROM {assign} a
724                            WHERE a.course=:course';
725             $params = array('course'=>$data->courseid);
727             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
729             $status[] = array('component'=>$componentstr,
730                               'item'=>get_string('deleteallsubmissions', 'assign'),
731                               'error'=>false);
733             if (!empty($data->reset_gradebook_grades)) {
734                 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
735                 // Remove all grades from gradebook.
736                 require_once($CFG->dirroot.'/mod/assign/lib.php');
737                 assign_reset_gradebook($data->courseid);
738             }
739         }
740         // Updating dates - shift may be negative too.
741         if ($data->timeshift) {
742             shift_course_mod_dates('assign',
743                                     array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
744                                     $data->timeshift,
745                                     $data->courseid);
746             $status[] = array('component'=>$componentstr,
747                               'item'=>get_string('datechanged'),
748                               'error'=>false);
749         }
751         return $status;
752     }
754     /**
755      * Update the settings for a single plugin.
756      *
757      * @param assign_plugin $plugin The plugin to update
758      * @param stdClass $formdata The form data
759      * @return bool false if an error occurs
760      */
761     protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
762         if ($plugin->is_visible()) {
763             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
764             if (!empty($formdata->$enabledname)) {
765                 $plugin->enable();
766                 if (!$plugin->save_settings($formdata)) {
767                     print_error($plugin->get_error());
768                     return false;
769                 }
770             } else {
771                 $plugin->disable();
772             }
773         }
774         return true;
775     }
777     /**
778      * Update the gradebook information for this assignment.
779      *
780      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
781      * @param int $coursemoduleid This is required because it might not exist in the database yet
782      * @return bool
783      */
784     public function update_gradebook($reset, $coursemoduleid) {
785         global $CFG;
787         require_once($CFG->dirroot.'/mod/assign/lib.php');
788         $assign = clone $this->get_instance();
789         $assign->cmidnumber = $coursemoduleid;
790         $param = null;
791         if ($reset) {
792             $param = 'reset';
793         }
795         return assign_grade_item_update($assign, $param);
796     }
798     /**
799      * Load and cache the admin config for this module.
800      *
801      * @return stdClass the plugin config
802      */
803     public function get_admin_config() {
804         if ($this->adminconfig) {
805             return $this->adminconfig;
806         }
807         $this->adminconfig = get_config('assign');
808         return $this->adminconfig;
809     }
811     /**
812      * Update the calendar entries for this assignment.
813      *
814      * @param int $coursemoduleid - Required to pass this in because it might
815      *                              not exist in the database yet.
816      * @return bool
817      */
818     public function update_calendar($coursemoduleid) {
819         global $DB, $CFG;
820         require_once($CFG->dirroot.'/calendar/lib.php');
822         // Special case for add_instance as the coursemodule has not been set yet.
823         $instance = $this->get_instance();
825         if ($instance->duedate) {
826             $event = new stdClass();
828             $params = array('modulename'=>'assign', 'instance'=>$instance->id);
829             $event->id = $DB->get_field('event',
830                                         'id',
831                                         $params);
833             if ($event->id) {
834                 $event->name        = $instance->name;
835                 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
836                 $event->timestart   = $instance->duedate;
838                 $calendarevent = calendar_event::load($event->id);
839                 $calendarevent->update($event);
840             } else {
841                 $event = new stdClass();
842                 $event->name        = $instance->name;
843                 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
844                 $event->courseid    = $instance->course;
845                 $event->groupid     = 0;
846                 $event->userid      = 0;
847                 $event->modulename  = 'assign';
848                 $event->instance    = $instance->id;
849                 $event->eventtype   = 'due';
850                 $event->timestart   = $instance->duedate;
851                 $event->timeduration = 0;
853                 calendar_event::create($event);
854             }
855         } else {
856             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
857         }
858     }
861     /**
862      * Update this instance in the database.
863      *
864      * @param stdClass $formdata - the data submitted from the form
865      * @return bool false if an error occurs
866      */
867     public function update_instance($formdata) {
868         global $DB;
870         $update = new stdClass();
871         $update->id = $formdata->instance;
872         $update->name = $formdata->name;
873         $update->timemodified = time();
874         $update->course = $formdata->course;
875         $update->intro = $formdata->intro;
876         $update->introformat = $formdata->introformat;
877         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
878         $update->submissiondrafts = $formdata->submissiondrafts;
879         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
880         $update->sendnotifications = $formdata->sendnotifications;
881         $update->sendlatenotifications = $formdata->sendlatenotifications;
882         $update->duedate = $formdata->duedate;
883         $update->cutoffdate = $formdata->cutoffdate;
884         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
885         $update->grade = $formdata->grade;
886         if (!empty($formdata->completionunlocked)) {
887             $update->completionsubmit = !empty($formdata->completionsubmit);
888         }
889         $update->teamsubmission = $formdata->teamsubmission;
890         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
891         if (isset($formdata->teamsubmissiongroupingid)) {
892             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
893         }
894         $update->blindmarking = $formdata->blindmarking;
895         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
896         if (!empty($formdata->attemptreopenmethod)) {
897             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
898         }
899         if (!empty($formdata->maxattempts)) {
900             $update->maxattempts = $formdata->maxattempts;
901         }
902         $update->markingworkflow = $formdata->markingworkflow;
903         $update->markingallocation = $formdata->markingallocation;
905         $result = $DB->update_record('assign', $update);
906         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
908         // Load the assignment so the plugins have access to it.
910         // Call save_settings hook for submission plugins.
911         foreach ($this->submissionplugins as $plugin) {
912             if (!$this->update_plugin_instance($plugin, $formdata)) {
913                 print_error($plugin->get_error());
914                 return false;
915             }
916         }
917         foreach ($this->feedbackplugins as $plugin) {
918             if (!$this->update_plugin_instance($plugin, $formdata)) {
919                 print_error($plugin->get_error());
920                 return false;
921             }
922         }
924         $this->update_calendar($this->get_course_module()->id);
925         $this->update_gradebook(false, $this->get_course_module()->id);
927         $update = new stdClass();
928         $update->id = $this->get_instance()->id;
929         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
930         $DB->update_record('assign', $update);
932         return $result;
933     }
935     /**
936      * Add elements in grading plugin form.
937      *
938      * @param mixed $grade stdClass|null
939      * @param MoodleQuickForm $mform
940      * @param stdClass $data
941      * @param int $userid - The userid we are grading
942      * @return void
943      */
944     protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
945         foreach ($this->feedbackplugins as $plugin) {
946             if ($plugin->is_enabled() && $plugin->is_visible()) {
947                 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
948                 $mform->setExpanded('header_' . $plugin->get_type());
949                 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
950                     $mform->removeElement('header_' . $plugin->get_type());
951                 }
952             }
953         }
954     }
958     /**
959      * Add one plugins settings to edit plugin form.
960      *
961      * @param assign_plugin $plugin The plugin to add the settings from
962      * @param MoodleQuickForm $mform The form to add the configuration settings to.
963      *                               This form is modified directly (not returned).
964      * @param array $pluginsenabled A list of form elements to be added to a group.
965      *                              The new element is added to this array by this function.
966      * @return void
967      */
968     protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
969         global $CFG;
970         if ($plugin->is_visible()) {
972             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
973             $label = $plugin->get_name();
974             $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
975             $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
977             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
978             if ($plugin->get_config('enabled') !== false) {
979                 $default = $plugin->is_enabled();
980             }
981             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
983             $plugin->get_settings($mform);
985         }
986     }
988     /**
989      * Add settings to edit plugin form.
990      *
991      * @param MoodleQuickForm $mform The form to add the configuration settings to.
992      *                               This form is modified directly (not returned).
993      * @return void
994      */
995     public function add_all_plugin_settings(MoodleQuickForm $mform) {
996         $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
998         $submissionpluginsenabled = array();
999         $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1000         foreach ($this->submissionplugins as $plugin) {
1001             $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1002         }
1003         $group->setElements($submissionpluginsenabled);
1005         $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1006         $feedbackpluginsenabled = array();
1007         $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1008         foreach ($this->feedbackplugins as $plugin) {
1009             $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1010         }
1011         $group->setElements($feedbackpluginsenabled);
1012         $mform->setExpanded('submissiontypes');
1013     }
1015     /**
1016      * Allow each plugin an opportunity to update the defaultvalues
1017      * passed in to the settings form (needed to set up draft areas for
1018      * editor and filemanager elements)
1019      *
1020      * @param array $defaultvalues
1021      */
1022     public function plugin_data_preprocessing(&$defaultvalues) {
1023         foreach ($this->submissionplugins as $plugin) {
1024             if ($plugin->is_visible()) {
1025                 $plugin->data_preprocessing($defaultvalues);
1026             }
1027         }
1028         foreach ($this->feedbackplugins as $plugin) {
1029             if ($plugin->is_visible()) {
1030                 $plugin->data_preprocessing($defaultvalues);
1031             }
1032         }
1033     }
1035     /**
1036      * Get the name of the current module.
1037      *
1038      * @return string the module name (Assignment)
1039      */
1040     protected function get_module_name() {
1041         if (isset(self::$modulename)) {
1042             return self::$modulename;
1043         }
1044         self::$modulename = get_string('modulename', 'assign');
1045         return self::$modulename;
1046     }
1048     /**
1049      * Get the plural name of the current module.
1050      *
1051      * @return string the module name plural (Assignments)
1052      */
1053     protected function get_module_name_plural() {
1054         if (isset(self::$modulenameplural)) {
1055             return self::$modulenameplural;
1056         }
1057         self::$modulenameplural = get_string('modulenameplural', 'assign');
1058         return self::$modulenameplural;
1059     }
1061     /**
1062      * Has this assignment been constructed from an instance?
1063      *
1064      * @return bool
1065      */
1066     public function has_instance() {
1067         return $this->instance || $this->get_course_module();
1068     }
1070     /**
1071      * Get the settings for the current instance of this assignment
1072      *
1073      * @return stdClass The settings
1074      */
1075     public function get_instance() {
1076         global $DB;
1077         if ($this->instance) {
1078             return $this->instance;
1079         }
1080         if ($this->get_course_module()) {
1081             $params = array('id' => $this->get_course_module()->instance);
1082             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1083         }
1084         if (!$this->instance) {
1085             throw new coding_exception('Improper use of the assignment class. ' .
1086                                        'Cannot load the assignment record.');
1087         }
1088         return $this->instance;
1089     }
1091     /**
1092      * Get the primary grade item for this assign instance.
1093      *
1094      * @return stdClass The grade_item record
1095      */
1096     public function get_grade_item() {
1097         if ($this->gradeitem) {
1098             return $this->gradeitem;
1099         }
1100         $instance = $this->get_instance();
1101         $params = array('itemtype' => 'mod',
1102                         'itemmodule' => 'assign',
1103                         'iteminstance' => $instance->id,
1104                         'courseid' => $instance->course,
1105                         'itemnumber' => 0);
1106         $this->gradeitem = grade_item::fetch($params);
1107         if (!$this->gradeitem) {
1108             throw new coding_exception('Improper use of the assignment class. ' .
1109                                        'Cannot load the grade item.');
1110         }
1111         return $this->gradeitem;
1112     }
1114     /**
1115      * Get the context of the current course.
1116      *
1117      * @return mixed context|null The course context
1118      */
1119     public function get_course_context() {
1120         if (!$this->context && !$this->course) {
1121             throw new coding_exception('Improper use of the assignment class. ' .
1122                                        'Cannot load the course context.');
1123         }
1124         if ($this->context) {
1125             return $this->context->get_course_context();
1126         } else {
1127             return context_course::instance($this->course->id);
1128         }
1129     }
1132     /**
1133      * Get the current course module.
1134      *
1135      * @return mixed stdClass|null The course module
1136      */
1137     public function get_course_module() {
1138         if ($this->coursemodule) {
1139             return $this->coursemodule;
1140         }
1141         if (!$this->context) {
1142             return null;
1143         }
1145         if ($this->context->contextlevel == CONTEXT_MODULE) {
1146             $this->coursemodule = get_coursemodule_from_id('assign',
1147                                                            $this->context->instanceid,
1148                                                            0,
1149                                                            false,
1150                                                            MUST_EXIST);
1151             return $this->coursemodule;
1152         }
1153         return null;
1154     }
1156     /**
1157      * Get context module.
1158      *
1159      * @return context
1160      */
1161     public function get_context() {
1162         return $this->context;
1163     }
1165     /**
1166      * Get the current course.
1167      *
1168      * @return mixed stdClass|null The course
1169      */
1170     public function get_course() {
1171         global $DB;
1173         if ($this->course) {
1174             return $this->course;
1175         }
1177         if (!$this->context) {
1178             return null;
1179         }
1180         $params = array('id' => $this->get_course_context()->instanceid);
1181         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1183         return $this->course;
1184     }
1186     /**
1187      * Return a grade in user-friendly form, whether it's a scale or not.
1188      *
1189      * @param mixed $grade int|null
1190      * @param boolean $editing Are we allowing changes to this grade?
1191      * @param int $userid The user id the grade belongs to
1192      * @param int $modified Timestamp from when the grade was last modified
1193      * @return string User-friendly representation of grade
1194      */
1195     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1196         global $DB;
1198         static $scalegrades = array();
1200         $o = '';
1202         if ($this->get_instance()->grade >= 0) {
1203             // Normal number.
1204             if ($editing && $this->get_instance()->grade > 0) {
1205                 if ($grade < 0) {
1206                     $displaygrade = '';
1207                 } else {
1208                     $displaygrade = format_float($grade, 2);
1209                 }
1210                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1211                        get_string('usergrade', 'assign') .
1212                        '</label>';
1213                 $o .= '<input type="text"
1214                               id="quickgrade_' . $userid . '"
1215                               name="quickgrade_' . $userid . '"
1216                               value="' .  $displaygrade . '"
1217                               size="6"
1218                               maxlength="10"
1219                               class="quickgrade"/>';
1220                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1221                 $o .= '<input type="hidden"
1222                               name="grademodified_' . $userid . '"
1223                               value="' . $modified . '"/>';
1224                 return $o;
1225             } else {
1226                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1227                 if ($grade == -1 || $grade === null) {
1228                     $o .= '-';
1229                 } else {
1230                     $item = $this->get_grade_item();
1231                     $o .= grade_format_gradevalue($grade, $item);
1232                     if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1233                         // If displaying the raw grade, also display the total value.
1234                         $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1235                     }
1236                 }
1237                 return $o;
1238             }
1240         } else {
1241             // Scale.
1242             if (empty($this->cache['scale'])) {
1243                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1244                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1245                 } else {
1246                     $o .= '-';
1247                     return $o;
1248                 }
1249             }
1250             if ($editing) {
1251                 $o .= '<label class="accesshide"
1252                               for="quickgrade_' . $userid . '">' .
1253                       get_string('usergrade', 'assign') .
1254                       '</label>';
1255                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1256                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1257                 foreach ($this->cache['scale'] as $optionid => $option) {
1258                     $selected = '';
1259                     if ($grade == $optionid) {
1260                         $selected = 'selected="selected"';
1261                     }
1262                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1263                 }
1264                 $o .= '</select>';
1265                 $o .= '<input type="hidden" ' .
1266                              'name="grademodified_' . $userid . '" ' .
1267                              'value="' . $modified . '"/>';
1268                 return $o;
1269             } else {
1270                 $scaleid = (int)$grade;
1271                 if (isset($this->cache['scale'][$scaleid])) {
1272                     $o .= $this->cache['scale'][$scaleid];
1273                     return $o;
1274                 }
1275                 $o .= '-';
1276                 return $o;
1277             }
1278         }
1279     }
1281     /**
1282      * Load a list of users enrolled in the current course with the specified permission and group.
1283      * 0 for no group.
1284      *
1285      * @param int $currentgroup
1286      * @param bool $idsonly
1287      * @return array List of user records
1288      */
1289     public function list_participants($currentgroup, $idsonly) {
1290         if ($idsonly) {
1291             $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.id', null, null, null,
1292                     $this->show_only_active_users());
1293         } else {
1294             $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', null, null, null,
1295                     $this->show_only_active_users());
1296         }
1298         $cm = $this->get_course_module();
1299         foreach ($users as $userid => $user) {
1300             if (!groups_course_module_visible($cm, $userid)) {
1301                 unset($users[$userid]);
1302             }
1303         }
1305         return $users;
1306     }
1308     /**
1309      * Load a count of valid teams for this assignment.
1310      *
1311      * @return int number of valid teams
1312      */
1313     public function count_teams() {
1315         $groups = groups_get_all_groups($this->get_course()->id,
1316                                         0,
1317                                         $this->get_instance()->teamsubmissiongroupingid,
1318                                         'g.id');
1319         $count = count($groups);
1321         // See if there are any users in the default group.
1322         $defaultusers = $this->get_submission_group_members(0, true);
1323         if (count($defaultusers) > 0) {
1324             $count += 1;
1325         }
1326         return $count;
1327     }
1329     /**
1330      * Load a count of active users enrolled in the current course with the specified permission and group.
1331      * 0 for no group.
1332      *
1333      * @param int $currentgroup
1334      * @return int number of matching users
1335      */
1336     public function count_participants($currentgroup) {
1337         return count($this->list_participants($currentgroup, true));
1338     }
1340     /**
1341      * Load a count of active users submissions in the current module that require grading
1342      * This means the submission modification time is more recent than the
1343      * grading modification time and the status is SUBMITTED.
1344      *
1345      * @return int number of matching submissions
1346      */
1347     public function count_submissions_need_grading() {
1348         global $DB;
1350         if ($this->get_instance()->teamsubmission) {
1351             // This does not make sense for group assignment because the submission is shared.
1352             return 0;
1353         }
1355         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1356         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1358         $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1359                                  FROM {assign_submission} mxs
1360                                  WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1361         $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1362                             FROM {assign_grades} mxg
1363                             WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1365         $params['assignid'] = $this->get_instance()->id;
1366         $params['assignid2'] = $this->get_instance()->id;
1367         $params['assignid3'] = $this->get_instance()->id;
1368         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1370         $sql = 'SELECT COUNT(s.userid)
1371                    FROM {assign_submission} s
1372                    LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1373                    LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1374                    LEFT JOIN {assign_grades} g ON
1375                         s.assignment = g.assignment AND
1376                         s.userid = g.userid AND
1377                         g.attemptnumber = gmx.maxattempt
1378                    JOIN(' . $esql . ') e ON e.id = s.userid
1379                    WHERE
1380                         s.attemptnumber = smx.maxattempt AND
1381                         s.assignment = :assignid AND
1382                         s.timemodified IS NOT NULL AND
1383                         s.status = :submitted AND
1384                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1386         return $DB->count_records_sql($sql, $params);
1387     }
1389     /**
1390      * Load a count of grades.
1391      *
1392      * @return int number of grades
1393      */
1394     public function count_grades() {
1395         global $DB;
1397         if (!$this->has_instance()) {
1398             return 0;
1399         }
1401         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1402         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1404         $params['assignid'] = $this->get_instance()->id;
1406         $sql = 'SELECT COUNT(g.userid)
1407                    FROM {assign_grades} g
1408                    JOIN(' . $esql . ') e ON e.id = g.userid
1409                    WHERE g.assignment = :assignid';
1411         return $DB->count_records_sql($sql, $params);
1412     }
1414     /**
1415      * Load a count of submissions.
1416      *
1417      * @return int number of submissions
1418      */
1419     public function count_submissions() {
1420         global $DB;
1422         if (!$this->has_instance()) {
1423             return 0;
1424         }
1426         $params = array();
1428         if ($this->get_instance()->teamsubmission) {
1429             // We cannot join on the enrolment tables for group submissions (no userid).
1430             $sql = 'SELECT COUNT(DISTINCT s.groupid)
1431                         FROM {assign_submission} s
1432                         WHERE
1433                             s.assignment = :assignid AND
1434                             s.timemodified IS NOT NULL AND
1435                             s.userid = :groupuserid';
1437             $params['assignid'] = $this->get_instance()->id;
1438             $params['groupuserid'] = 0;
1439         } else {
1440             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1441             list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1443             $params['assignid'] = $this->get_instance()->id;
1445             $sql = 'SELECT COUNT(DISTINCT s.userid)
1446                        FROM {assign_submission} s
1447                        JOIN(' . $esql . ') e ON e.id = s.userid
1448                        WHERE
1449                             s.assignment = :assignid AND
1450                             s.timemodified IS NOT NULL';
1452         }
1454         return $DB->count_records_sql($sql, $params);
1455     }
1457     /**
1458      * Load a count of submissions with a specified status.
1459      *
1460      * @param string $status The submission status - should match one of the constants
1461      * @return int number of matching submissions
1462      */
1463     public function count_submissions_with_status($status) {
1464         global $DB;
1466         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1467         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1469         $params['assignid'] = $this->get_instance()->id;
1470         $params['assignid2'] = $this->get_instance()->id;
1471         $params['submissionstatus'] = $status;
1473         if ($this->get_instance()->teamsubmission) {
1474             $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1475                               FROM {assign_submission} mxs
1476                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1478             $sql = 'SELECT COUNT(s.groupid)
1479                         FROM {assign_submission} s
1480                         JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1481                         WHERE
1482                             s.attemptnumber = smx.maxattempt AND
1483                             s.assignment = :assignid AND
1484                             s.timemodified IS NOT NULL AND
1485                             s.userid = :groupuserid AND
1486                             s.status = :submissionstatus';
1487             $params['groupuserid'] = 0;
1488         } else {
1489             $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1490                               FROM {assign_submission} mxs
1491                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1493             $sql = 'SELECT COUNT(s.userid)
1494                         FROM {assign_submission} s
1495                         JOIN(' . $esql . ') e ON e.id = s.userid
1496                         JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1497                         WHERE
1498                             s.attemptnumber = smx.maxattempt AND
1499                             s.assignment = :assignid AND
1500                             s.timemodified IS NOT NULL AND
1501                             s.status = :submissionstatus';
1503         }
1505         return $DB->count_records_sql($sql, $params);
1506     }
1508     /**
1509      * Utility function to get the userid for every row in the grading table
1510      * so the order can be frozen while we iterate it.
1511      *
1512      * @return array An array of userids
1513      */
1514     protected function get_grading_userid_list() {
1515         $filter = get_user_preferences('assign_filter', '');
1516         $table = new assign_grading_table($this, 0, $filter, 0, false);
1518         $useridlist = $table->get_column_data('userid');
1520         return $useridlist;
1521     }
1523     /**
1524      * Generate zip file from array of given files.
1525      *
1526      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1527      *                                 This array is indexed by the final file name and each
1528      *                                 element in the array is an instance of a stored_file object.
1529      * @return path of temp file - note this returned file does
1530      *         not have a .zip extension - it is a temp file.
1531      */
1532     protected function pack_files($filesforzipping) {
1533         global $CFG;
1534         // Create path for new zip file.
1535         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1536         // Zip files.
1537         $zipper = new zip_packer();
1538         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1539             return $tempzip;
1540         }
1541         return false;
1542     }
1544     /**
1545      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1546      *
1547      * Cron function to be run periodically according to the moodle cron.
1548      *
1549      * @return bool
1550      */
1551     public static function cron() {
1552         global $DB;
1554         // Only ever send a max of one days worth of updates.
1555         $yesterday = time() - (24 * 3600);
1556         $timenow   = time();
1558         // Collect all submissions from the past 24 hours that require mailing.
1559         $sql = 'SELECT a.course, a.name, a.blindmarking, a.revealidentities,
1560                        g.*, g.id as gradeid, g.timemodified as lastmodified
1561                  FROM {assign} a
1562                  JOIN {assign_grades} g ON g.assignment = a.id
1563                  LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1564                 WHERE g.timemodified >= :yesterday AND
1565                       g.timemodified <= :today AND
1566                       uf.mailed = 0';
1568         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1569         $submissions = $DB->get_records_sql($sql, $params);
1571         if (empty($submissions)) {
1572             return true;
1573         }
1575         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1577         // Preload courses we are going to need those.
1578         $courseids = array();
1579         foreach ($submissions as $submission) {
1580             $courseids[] = $submission->course;
1581         }
1583         // Filter out duplicates.
1584         $courseids = array_unique($courseids);
1585         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1586         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1587         $sql = 'SELECT c.*, ' . $ctxselect .
1588                   ' FROM {course} c
1589              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1590                  WHERE c.id ' . $courseidsql;
1592         $params['contextlevel'] = CONTEXT_COURSE;
1593         $courses = $DB->get_records_sql($sql, $params);
1595         // Clean up... this could go on for a while.
1596         unset($courseids);
1597         unset($ctxselect);
1598         unset($courseidsql);
1599         unset($params);
1601         // Simple array we'll use for caching modules.
1602         $modcache = array();
1604         // Message students about new feedback.
1605         foreach ($submissions as $submission) {
1607             mtrace("Processing assignment submission $submission->id ...");
1609             // Do not cache user lookups - could be too many.
1610             if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1611                 mtrace('Could not find user ' . $submission->userid);
1612                 continue;
1613             }
1615             // Use a cache to prevent the same DB queries happening over and over.
1616             if (!array_key_exists($submission->course, $courses)) {
1617                 mtrace('Could not find course ' . $submission->course);
1618                 continue;
1619             }
1620             $course = $courses[$submission->course];
1621             if (isset($course->ctxid)) {
1622                 // Context has not yet been preloaded. Do so now.
1623                 context_helper::preload_from_record($course);
1624             }
1626             // Override the language and timezone of the "current" user, so that
1627             // mail is customised for the receiver.
1628             cron_setup_user($user, $course);
1630             // Context lookups are already cached.
1631             $coursecontext = context_course::instance($course->id);
1632             if (!is_enrolled($coursecontext, $user->id)) {
1633                 $courseshortname = format_string($course->shortname,
1634                                                  true,
1635                                                  array('context' => $coursecontext));
1636                 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1637                 continue;
1638             }
1640             if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1641                 mtrace('Could not find grader ' . $submission->grader);
1642                 continue;
1643             }
1645             if (!array_key_exists($submission->assignment, $modcache)) {
1646                 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1647                 if (empty($mod)) {
1648                     mtrace('Could not find course module for assignment id ' . $submission->assignment);
1649                     continue;
1650                 }
1651                 $modcache[$submission->assignment] = $mod;
1652             } else {
1653                 $mod = $modcache[$submission->assignment];
1654             }
1655             // Context lookups are already cached.
1656             $contextmodule = context_module::instance($mod->id);
1658             if (!$mod->visible) {
1659                 // Hold mail notification for hidden assignments until later.
1660                 continue;
1661             }
1663             // Need to send this to the student.
1664             $messagetype = 'feedbackavailable';
1665             $eventtype = 'assign_notification';
1666             $updatetime = $submission->lastmodified;
1667             $modulename = get_string('modulename', 'assign');
1669             $uniqueid = 0;
1670             if ($submission->blindmarking && !$submission->revealidentities) {
1671                 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1672             }
1673             $showusers = $submission->blindmarking && !$submission->revealidentities;
1674             self::send_assignment_notification($grader,
1675                                                $user,
1676                                                $messagetype,
1677                                                $eventtype,
1678                                                $updatetime,
1679                                                $mod,
1680                                                $contextmodule,
1681                                                $course,
1682                                                $modulename,
1683                                                $submission->name,
1684                                                $showusers,
1685                                                $uniqueid);
1687             $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1688             if ($flags) {
1689                 $flags->mailed = 1;
1690                 $DB->update_record('assign_user_flags', $flags);
1691             } else {
1692                 $flags = new stdClass();
1693                 $flags->userid = $user->id;
1694                 $flags->assignment = $submission->assignment;
1695                 $flags->mailed = 1;
1696                 $DB->insert_record('assign_user_flags', $flags);
1697             }
1699             mtrace('Done');
1700         }
1701         mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1703         cron_setup_user();
1705         // Free up memory just to be sure.
1706         unset($courses);
1707         unset($modcache);
1709         return true;
1710     }
1712     /**
1713      * Mark in the database that this grade record should have an update notification sent by cron.
1714      *
1715      * @param stdClass $grade a grade record keyed on id
1716      * @return bool true for success
1717      */
1718     public function notify_grade_modified($grade) {
1719         global $DB;
1721         $flags = $this->get_user_flags($grade->userid, true);
1722         if ($flags->mailed != 1) {
1723             $flags->mailed = 0;
1724         }
1726         return $this->update_user_flags($flags);
1727     }
1729     /**
1730      * Update user flags for this user in this assignment.
1731      *
1732      * @param stdClass $flags a flags record keyed on id
1733      * @return bool true for success
1734      */
1735     public function update_user_flags($flags) {
1736         global $DB;
1737         if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1738             return false;
1739         }
1741         $result = $DB->update_record('assign_user_flags', $flags);
1742         return $result;
1743     }
1745     /**
1746      * Update a grade in the grade table for the assignment and in the gradebook.
1747      *
1748      * @param stdClass $grade a grade record keyed on id
1749      * @return bool true for success
1750      */
1751     public function update_grade($grade) {
1752         global $DB;
1754         $grade->timemodified = time();
1756         if (!empty($grade->workflowstate)) {
1757             $validstates = $this->get_marking_workflow_states_for_current_user();
1758             if (!array_key_exists($grade->workflowstate, $validstates)) {
1759                 return false;
1760             }
1761         }
1763         if ($grade->grade && $grade->grade != -1) {
1764             if ($this->get_instance()->grade > 0) {
1765                 if (!is_numeric($grade->grade)) {
1766                     return false;
1767                 } else if ($grade->grade > $this->get_instance()->grade) {
1768                     return false;
1769                 } else if ($grade->grade < 0) {
1770                     return false;
1771                 }
1772             } else {
1773                 // This is a scale.
1774                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1775                     $scaleoptions = make_menu_from_list($scale->scale);
1776                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1777                         return false;
1778                     }
1779                 }
1780             }
1781         }
1783         if (empty($grade->attemptnumber)) {
1784             // Set it to the default.
1785             $grade->attemptnumber = 0;
1786         }
1787         $result = $DB->update_record('assign_grades', $grade);
1789         // Only push to gradebook if the update is for the latest attempt.
1790         $submission = null;
1791         if ($this->get_instance()->teamsubmission) {
1792             $submission = $this->get_group_submission($grade->userid, 0, false);
1793         } else {
1794             $submission = $this->get_user_submission($grade->userid, false);
1795         }
1796         // Not the latest attempt.
1797         if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1798             return true;
1799         }
1801         if ($result) {
1802             $this->gradebook_item_update(null, $grade);
1803         }
1804         return $result;
1805     }
1807     /**
1808      * View the grant extension date page.
1809      *
1810      * Uses url parameters 'userid'
1811      * or from parameter 'selectedusers'
1812      *
1813      * @param moodleform $mform - Used for validation of the submitted data
1814      * @return string
1815      */
1816     protected function view_grant_extension($mform) {
1817         global $DB, $CFG;
1818         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1820         $o = '';
1821         $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1822         $data = new stdClass();
1823         $data->extensionduedate = null;
1824         $userid = 0;
1825         if (!$batchusers) {
1826             $userid = required_param('userid', PARAM_INT);
1828             $grade = $this->get_user_grade($userid, false);
1830             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1832             if ($grade) {
1833                 $data->extensionduedate = $grade->extensionduedate;
1834             }
1835             $data->userid = $userid;
1836         } else {
1837             $data->batchusers = $batchusers;
1838         }
1839         $header = new assign_header($this->get_instance(),
1840                                     $this->get_context(),
1841                                     $this->show_intro(),
1842                                     $this->get_course_module()->id,
1843                                     get_string('grantextension', 'assign'));
1844         $o .= $this->get_renderer()->render($header);
1846         if (!$mform) {
1847             $formparams = array($this->get_course_module()->id,
1848                                 $userid,
1849                                 $batchusers,
1850                                 $this->get_instance(),
1851                                 $data);
1852             $mform = new mod_assign_extension_form(null, $formparams);
1853         }
1854         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1855         $o .= $this->view_footer();
1856         return $o;
1857     }
1859     /**
1860      * Get a list of the users in the same group as this user.
1861      *
1862      * @param int $groupid The id of the group whose members we want or 0 for the default group
1863      * @param bool $onlyids Whether to retrieve only the user id's
1864      * @return array The users (possibly id's only)
1865      */
1866     public function get_submission_group_members($groupid, $onlyids) {
1867         $members = array();
1868         if ($groupid != 0) {
1869             if ($onlyids) {
1870                 $allusers = groups_get_members($groupid, 'u.id');
1871             } else {
1872                 $allusers = groups_get_members($groupid);
1873             }
1874             foreach ($allusers as $user) {
1875                 if ($this->get_submission_group($user->id)) {
1876                     $members[] = $user;
1877                 }
1878             }
1879         } else {
1880             $allusers = $this->list_participants(null, $onlyids);
1881             foreach ($allusers as $user) {
1882                 if ($this->get_submission_group($user->id) == null) {
1883                     $members[] = $user;
1884                 }
1885             }
1886         }
1887         // Exclude suspended users, if user can't see them.
1888         if (!has_capability('moodle/course:viewsuspendedusers', $this->context)) {
1889             foreach ($members as $key => $member) {
1890                 if (!$this->is_active_user($member->id)) {
1891                     unset($members[$key]);
1892                 }
1893             }
1894         }
1895         return $members;
1896     }
1898     /**
1899      * Get a list of the users in the same group as this user that have not submitted the assignment.
1900      *
1901      * @param int $groupid The id of the group whose members we want or 0 for the default group
1902      * @param bool $onlyids Whether to retrieve only the user id's
1903      * @return array The users (possibly id's only)
1904      */
1905     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1906         $instance = $this->get_instance();
1907         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1908             return array();
1909         }
1910         $members = $this->get_submission_group_members($groupid, $onlyids);
1912         foreach ($members as $id => $member) {
1913             $submission = $this->get_user_submission($member->id, false);
1914             if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1915                 unset($members[$id]);
1916             } else {
1917                 if ($this->is_blind_marking()) {
1918                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
1919                                            $this->get_uniqueid_for_user($id);
1920                 }
1921             }
1922         }
1923         return $members;
1924     }
1926     /**
1927      * Load the group submission object for a particular user, optionally creating it if required.
1928      *
1929      * @param int $userid The id of the user whose submission we want
1930      * @param int $groupid The id of the group for this user - may be 0 in which
1931      *                     case it is determined from the userid.
1932      * @param bool $create If set to true a new submission object will be created in the database
1933      * @param int $attemptnumber - -1 means the latest attempt
1934      * @return stdClass The submission
1935      */
1936     public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
1937         global $DB;
1939         if ($groupid == 0) {
1940             $group = $this->get_submission_group($userid);
1941             if ($group) {
1942                 $groupid = $group->id;
1943             }
1944         }
1946         // Now get the group submission.
1947         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1948         if ($attemptnumber >= 0) {
1949             $params['attemptnumber'] = $attemptnumber;
1950         }
1952         // Only return the row with the highest attemptnumber.
1953         $submission = null;
1954         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
1955         if ($submissions) {
1956             $submission = reset($submissions);
1957         }
1959         if ($submission) {
1960             return $submission;
1961         }
1962         if ($create) {
1963             $submission = new stdClass();
1964             $submission->assignment = $this->get_instance()->id;
1965             $submission->userid = 0;
1966             $submission->groupid = $groupid;
1967             $submission->timecreated = time();
1968             $submission->timemodified = $submission->timecreated;
1969             if ($attemptnumber >= 0) {
1970                 $submission->attemptnumber = $attemptnumber;
1971             } else {
1972                 $submission->attemptnumber = 0;
1973             }
1975             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1976             $sid = $DB->insert_record('assign_submission', $submission);
1977             $submission->id = $sid;
1978             return $submission;
1979         }
1980         return false;
1981     }
1983     /**
1984      * View a summary listing of all assignments in the current course.
1985      *
1986      * @return string
1987      */
1988     private function view_course_index() {
1989         global $USER;
1991         $o = '';
1993         $course = $this->get_course();
1994         $strplural = get_string('modulenameplural', 'assign');
1996         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
1997             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
1998             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
1999             return $o;
2000         }
2002         $strsectionname  = get_string('sectionname', 'format_'.$course->format);
2003         $usesections = course_format_uses_sections($course->format);
2004         $modinfo = get_fast_modinfo($course);
2006         if ($usesections) {
2007             $sections = $modinfo->get_section_info_all();
2008         }
2009         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2011         $timenow = time();
2013         $currentsection = '';
2014         foreach ($modinfo->instances['assign'] as $cm) {
2015             if (!$cm->uservisible) {
2016                 continue;
2017             }
2019             $timedue = $cms[$cm->id]->duedate;
2021             $sectionname = '';
2022             if ($usesections && $cm->sectionnum) {
2023                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2024             }
2026             $submitted = '';
2027             $context = context_module::instance($cm->id);
2029             $assignment = new assign($context, $cm, $course);
2031             if (has_capability('mod/assign:grade', $context)) {
2032                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2034             } else if (has_capability('mod/assign:submit', $context)) {
2035                 $usersubmission = $assignment->get_user_submission($USER->id, false);
2037                 if (!empty($usersubmission->status)) {
2038                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2039                 } else {
2040                     $submitted = get_string('submissionstatus_', 'assign');
2041                 }
2042             }
2043             $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2044             if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2045                     !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2046                 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2047             } else {
2048                 $grade = '-';
2049             }
2051             $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2053         }
2055         $o .= $this->get_renderer()->render($courseindexsummary);
2056         $o .= $this->view_footer();
2058         return $o;
2059     }
2061     /**
2062      * View a page rendered by a plugin.
2063      *
2064      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2065      *
2066      * @return string
2067      */
2068     protected function view_plugin_page() {
2069         global $USER;
2071         $o = '';
2073         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2074         $plugintype = required_param('plugin', PARAM_TEXT);
2075         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2077         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2078         if (!$plugin) {
2079             print_error('invalidformdata', '');
2080             return;
2081         }
2083         $o .= $plugin->view_page($pluginaction);
2085         return $o;
2086     }
2089     /**
2090      * This is used for team assignments to get the group for the specified user.
2091      * If the user is a member of multiple or no groups this will return false
2092      *
2093      * @param int $userid The id of the user whose submission we want
2094      * @return mixed The group or false
2095      */
2096     public function get_submission_group($userid) {
2097         $grouping = $this->get_instance()->teamsubmissiongroupingid;
2098         $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2099         if (count($groups) != 1) {
2100             return false;
2101         }
2102         return array_pop($groups);
2103     }
2106     /**
2107      * Display the submission that is used by a plugin.
2108      *
2109      * Uses url parameters 'sid', 'gid' and 'plugin'.
2110      *
2111      * @param string $pluginsubtype
2112      * @return string
2113      */
2114     protected function view_plugin_content($pluginsubtype) {
2115         global $USER;
2117         $o = '';
2119         $submissionid = optional_param('sid', 0, PARAM_INT);
2120         $gradeid = optional_param('gid', 0, PARAM_INT);
2121         $plugintype = required_param('plugin', PARAM_TEXT);
2122         $item = null;
2123         if ($pluginsubtype == 'assignsubmission') {
2124             $plugin = $this->get_submission_plugin_by_type($plugintype);
2125             if ($submissionid <= 0) {
2126                 throw new coding_exception('Submission id should not be 0');
2127             }
2128             $item = $this->get_submission($submissionid);
2130             // Check permissions.
2131             if ($item->userid != $USER->id) {
2132                 require_capability('mod/assign:grade', $this->context);
2133             }
2134             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2135                                                               $this->get_context(),
2136                                                               $this->show_intro(),
2137                                                               $this->get_course_module()->id,
2138                                                               $plugin->get_name()));
2139             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2140                                                               $item,
2141                                                               assign_submission_plugin_submission::FULL,
2142                                                               $this->get_course_module()->id,
2143                                                               $this->get_return_action(),
2144                                                               $this->get_return_params()));
2146             $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
2147             $this->add_to_log('view submission', $logmessage);
2148         } else {
2149             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2150             if ($gradeid <= 0) {
2151                 throw new coding_exception('Grade id should not be 0');
2152             }
2153             $item = $this->get_grade($gradeid);
2154             // Check permissions.
2155             if ($item->userid != $USER->id) {
2156                 require_capability('mod/assign:grade', $this->context);
2157             }
2158             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2159                                                               $this->get_context(),
2160                                                               $this->show_intro(),
2161                                                               $this->get_course_module()->id,
2162                                                               $plugin->get_name()));
2163             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2164                                                               $item,
2165                                                               assign_feedback_plugin_feedback::FULL,
2166                                                               $this->get_course_module()->id,
2167                                                               $this->get_return_action(),
2168                                                               $this->get_return_params()));
2169             $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
2170             $this->add_to_log('view feedback', $logmessage);
2171         }
2173         $o .= $this->view_return_links();
2175         $o .= $this->view_footer();
2176         return $o;
2177     }
2179     /**
2180      * Rewrite plugin file urls so they resolve correctly in an exported zip.
2181      *
2182      * @param string $text - The replacement text
2183      * @param stdClass $user - The user record
2184      * @param assign_plugin $plugin - The assignment plugin
2185      */
2186     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2187         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2188         $groupname = '';
2189         if ($groupmode) {
2190             $groupid = groups_get_activity_group($this->get_course_module(), true);
2191             $groupname = groups_get_group_name($groupid).'-';
2192         }
2194         if ($this->is_blind_marking()) {
2195             $prefix = $groupname . get_string('participant', 'assign');
2196             $prefix = str_replace('_', ' ', $prefix);
2197             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2198         } else {
2199             $prefix = $groupname . fullname($user);
2200             $prefix = str_replace('_', ' ', $prefix);
2201             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2202         }
2204         $subtype = $plugin->get_subtype();
2205         $type = $plugin->get_type();
2206         $prefix = $prefix . $subtype . '_' . $type . '_';
2208         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2210         return $result;
2211     }
2213     /**
2214      * Render the content in editor that is often used by plugin.
2215      *
2216      * @param string $filearea
2217      * @param int  $submissionid
2218      * @param string $plugintype
2219      * @param string $editor
2220      * @param string $component
2221      * @return string
2222      */
2223     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2224         global $CFG;
2226         $result = '';
2228         $plugin = $this->get_submission_plugin_by_type($plugintype);
2230         $text = $plugin->get_editor_text($editor, $submissionid);
2231         $format = $plugin->get_editor_format($editor, $submissionid);
2233         $finaltext = file_rewrite_pluginfile_urls($text,
2234                                                   'pluginfile.php',
2235                                                   $this->get_context()->id,
2236                                                   $component,
2237                                                   $filearea,
2238                                                   $submissionid);
2239         $params = array('overflowdiv' => true, 'context' => $this->get_context());
2240         $result .= format_text($finaltext, $format, $params);
2242         if ($CFG->enableportfolios) {
2243             require_once($CFG->libdir . '/portfoliolib.php');
2245             $button = new portfolio_add_button();
2246             $portfolioparams = array('cmid' => $this->get_course_module()->id,
2247                                      'sid' => $submissionid,
2248                                      'plugin' => $plugintype,
2249                                      'editor' => $editor,
2250                                      'area'=>$filearea);
2251             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2252             $fs = get_file_storage();
2254             if ($files = $fs->get_area_files($this->context->id,
2255                                              $component,
2256                                              $filearea,
2257                                              $submissionid,
2258                                              'timemodified',
2259                                              false)) {
2260                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2261             } else {
2262                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2263             }
2264             $result .= $button->to_html();
2265         }
2266         return $result;
2267     }
2269     /**
2270      * Display a continue page.
2271      *
2272      * @param string $message - The message to display
2273      * @return string
2274      */
2275     protected function view_savegrading_result($message) {
2276         $o = '';
2277         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2278                                                       $this->get_context(),
2279                                                       $this->show_intro(),
2280                                                       $this->get_course_module()->id,
2281                                                       get_string('savegradingresult', 'assign')));
2282         $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2283                                                    $message,
2284                                                    $this->get_course_module()->id);
2285         $o .= $this->get_renderer()->render($gradingresult);
2286         $o .= $this->view_footer();
2287         return $o;
2288     }
2289     /**
2290      * Display a grading error.
2291      *
2292      * @param string $message - The description of the result
2293      * @return string
2294      */
2295     protected function view_quickgrading_result($message) {
2296         $o = '';
2297         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2298                                                       $this->get_context(),
2299                                                       $this->show_intro(),
2300                                                       $this->get_course_module()->id,
2301                                                       get_string('quickgradingresult', 'assign')));
2302         $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2303                                                    $message,
2304                                                    $this->get_course_module()->id);
2305         $o .= $this->get_renderer()->render($gradingresult);
2306         $o .= $this->view_footer();
2307         return $o;
2308     }
2310     /**
2311      * Display the page footer.
2312      *
2313      * @return string
2314      */
2315     protected function view_footer() {
2316         return $this->get_renderer()->render_footer();
2317     }
2319     /**
2320      * Does this user have grade permission for this assignment?
2321      *
2322      * @return bool
2323      */
2324     public function can_grade() {
2325         // Permissions check.
2326         if (!has_capability('mod/assign:grade', $this->context)) {
2327             return false;
2328         }
2330         return true;
2331     }
2333     /**
2334      * Download a zip file of all assignment submissions.
2335      *
2336      * @return string - If an error occurs, this will contain the error page.
2337      */
2338     protected function download_submissions() {
2339         global $CFG, $DB;
2341         // More efficient to load this here.
2342         require_once($CFG->libdir.'/filelib.php');
2344         require_capability('mod/assign:grade', $this->context);
2346         // Load all users with submit.
2347         $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2348                         $this->show_only_active_users());
2350         // Build a list of files to zip.
2351         $filesforzipping = array();
2352         $fs = get_file_storage();
2354         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2355         // All users.
2356         $groupid = 0;
2357         $groupname = '';
2358         if ($groupmode) {
2359             $groupid = groups_get_activity_group($this->get_course_module(), true);
2360             $groupname = groups_get_group_name($groupid).'-';
2361         }
2363         // Construct the zip file name.
2364         $filename = clean_filename($this->get_course()->shortname . '-' .
2365                                    $this->get_instance()->name . '-' .
2366                                    $groupname.$this->get_course_module()->id . '.zip');
2368         // Get all the files for each student.
2369         foreach ($students as $student) {
2370             $userid = $student->id;
2372             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2373                 // Get the plugins to add their own files to the zip.
2375                 $submissiongroup = false;
2376                 $groupname = '';
2377                 if ($this->get_instance()->teamsubmission) {
2378                     $submission = $this->get_group_submission($userid, 0, false);
2379                     $submissiongroup = $this->get_submission_group($userid);
2380                     if ($submissiongroup) {
2381                         $groupname = $submissiongroup->name . '-';
2382                     } else {
2383                         $groupname = get_string('defaultteam', 'assign') . '-';
2384                     }
2385                 } else {
2386                     $submission = $this->get_user_submission($userid, false);
2387                 }
2389                 if ($this->is_blind_marking()) {
2390                     $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2391                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2392                 } else {
2393                     $prefix = str_replace('_', ' ', $groupname . fullname($student));
2394                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2395                 }
2397                 if ($submission) {
2398                     foreach ($this->submissionplugins as $plugin) {
2399                         if ($plugin->is_enabled() && $plugin->is_visible()) {
2400                             $pluginfiles = $plugin->get_files($submission, $student);
2401                             foreach ($pluginfiles as $zipfilename => $file) {
2402                                 $subtype = $plugin->get_subtype();
2403                                 $type = $plugin->get_type();
2404                                 $prefixedfilename = clean_filename($prefix .
2405                                                                    $subtype .
2406                                                                    '_' .
2407                                                                    $type .
2408                                                                    '_' .
2409                                                                    $zipfilename);
2410                                 $filesforzipping[$prefixedfilename] = $file;
2411                             }
2412                         }
2413                     }
2414                 }
2415             }
2416         }
2417         $result = '';
2418         if (count($filesforzipping) == 0) {
2419             $header = new assign_header($this->get_instance(),
2420                                         $this->get_context(),
2421                                         '',
2422                                         $this->get_course_module()->id,
2423                                         get_string('downloadall', 'assign'));
2424             $result .= $this->get_renderer()->render($header);
2425             $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2426             $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2427                                                                     'action'=>'grading'));
2428             $result .= $this->get_renderer()->continue_button($url);
2429             $result .= $this->view_footer();
2430         } else if ($zipfile = $this->pack_files($filesforzipping)) {
2431             $addtolog = $this->add_to_log('download all submissions', get_string('downloadall', 'assign'), '', true);
2432             $params = array(
2433                 'context' => $this->context,
2434                 'objectid' => $this->get_instance()->id
2435             );
2436             $event = \mod_assign\event\all_submissions_downloaded::create($params);
2437             $event->set_legacy_logdata($addtolog);
2438             $event->trigger();
2439             // Send file and delete after sending.
2440             send_temp_file($zipfile, $filename);
2441             // We will not get here - send_temp_file calls exit.
2442         }
2443         return $result;
2444     }
2446     /**
2447      * Util function to add a message to the log.
2448      *
2449      * @param string $action The current action
2450      * @param string $info A detailed description of the change. But no more than 255 characters.
2451      * @param string $url The url to the assign module instance.
2452      * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2453      *                     retrieve the arguments to use them with the new event system (Event 2).
2454      * @return void|array
2455      */
2456     public function add_to_log($action = '', $info = '', $url='', $return = false) {
2457         global $USER;
2459         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2460         if ($url != '') {
2461             $fullurl .= '&' . $url;
2462         }
2464         $args = array(
2465             $this->get_course()->id,
2466             'assign',
2467             $action,
2468             $fullurl,
2469             $info,
2470             $this->get_course_module()->id,
2471             $USER->id
2472         );
2474         if ($return) {
2475             return $args;
2476         }
2477         call_user_func_array('add_to_log', $args);
2478     }
2480     /**
2481      * Lazy load the page renderer and expose the renderer to plugins.
2482      *
2483      * @return assign_renderer
2484      */
2485     public function get_renderer() {
2486         global $PAGE;
2487         if ($this->output) {
2488             return $this->output;
2489         }
2490         $this->output = $PAGE->get_renderer('mod_assign');
2491         return $this->output;
2492     }
2494     /**
2495      * Load the submission object for a particular user, optionally creating it if required.
2496      *
2497      * For team assignments there are 2 submissions - the student submission and the team submission
2498      * All files are associated with the team submission but the status of the students contribution is
2499      * recorded separately.
2500      *
2501      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2502      * @param bool $create optional - defaults to false. If set to true a new submission object
2503      *                     will be created in the database.
2504      * @param int $attemptnumber - -1 means the latest attempt
2505      * @return stdClass The submission
2506      */
2507     public function get_user_submission($userid, $create, $attemptnumber=-1) {
2508         global $DB, $USER;
2510         if (!$userid) {
2511             $userid = $USER->id;
2512         }
2513         // If the userid is not null then use userid.
2514         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2515         if ($attemptnumber >= 0) {
2516             $params['attemptnumber'] = $attemptnumber;
2517         }
2519         // Only return the row with the highest attemptnumber.
2520         $submission = null;
2521         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2522         if ($submissions) {
2523             $submission = reset($submissions);
2524         }
2526         if ($submission) {
2527             return $submission;
2528         }
2529         if ($create) {
2530             $submission = new stdClass();
2531             $submission->assignment   = $this->get_instance()->id;
2532             $submission->userid       = $userid;
2533             $submission->timecreated = time();
2534             $submission->timemodified = $submission->timecreated;
2535             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2536             if ($attemptnumber >= 0) {
2537                 $submission->attemptnumber = $attemptnumber;
2538             } else {
2539                 $submission->attemptnumber = 0;
2540             }
2541             $sid = $DB->insert_record('assign_submission', $submission);
2542             $submission->id = $sid;
2543             return $submission;
2544         }
2545         return false;
2546     }
2548     /**
2549      * Load the submission object from it's id.
2550      *
2551      * @param int $submissionid The id of the submission we want
2552      * @return stdClass The submission
2553      */
2554     protected function get_submission($submissionid) {
2555         global $DB;
2557         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2558         return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2559     }
2561     /**
2562      * This will retrieve a user flags object from the db optionally creating it if required.
2563      * The user flags was split from the user_grades table in 2.5.
2564      *
2565      * @param int $userid The user we are getting the flags for.
2566      * @param bool $create If true the flags record will be created if it does not exist
2567      * @return stdClass The flags record
2568      */
2569     public function get_user_flags($userid, $create) {
2570         global $DB, $USER;
2572         // If the userid is not null then use userid.
2573         if (!$userid) {
2574             $userid = $USER->id;
2575         }
2577         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2579         $flags = $DB->get_record('assign_user_flags', $params);
2581         if ($flags) {
2582             return $flags;
2583         }
2584         if ($create) {
2585             $flags = new stdClass();
2586             $flags->assignment = $this->get_instance()->id;
2587             $flags->userid = $userid;
2588             $flags->locked = 0;
2589             $flags->extensionduedate = 0;
2590             $flags->workflowstate = '';
2591             $flags->allocatedmarker = 0;
2593             // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2594             // This is because students only want to be notified about certain types of update (grades and feedback).
2595             $flags->mailed = 2;
2597             $fid = $DB->insert_record('assign_user_flags', $flags);
2598             $flags->id = $fid;
2599             return $flags;
2600         }
2601         return false;
2602     }
2604     /**
2605      * This will retrieve a grade object from the db, optionally creating it if required.
2606      *
2607      * @param int $userid The user we are grading
2608      * @param bool $create If true the grade will be created if it does not exist
2609      * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2610      * @return stdClass The grade record
2611      */
2612     public function get_user_grade($userid, $create, $attemptnumber=-1) {
2613         global $DB, $USER;
2615         // If the userid is not null then use userid.
2616         if (!$userid) {
2617             $userid = $USER->id;
2618         }
2620         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2621         if ($attemptnumber < 0) {
2622             // Make sure this grade matches the latest submission attempt.
2623             if ($this->get_instance()->teamsubmission) {
2624                 $submission = $this->get_group_submission($userid, 0, false);
2625             } else {
2626                 $submission = $this->get_user_submission($userid, false);
2627             }
2628             if ($submission) {
2629                 $attemptnumber = $submission->attemptnumber;
2630             }
2631         }
2633         if ($attemptnumber >= 0) {
2634             $params['attemptnumber'] = $attemptnumber;
2635         }
2637         $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2639         if ($grades) {
2640             return reset($grades);
2641         }
2642         if ($create) {
2643             $grade = new stdClass();
2644             $grade->assignment   = $this->get_instance()->id;
2645             $grade->userid       = $userid;
2646             $grade->timecreated = time();
2647             $grade->timemodified = $grade->timecreated;
2648             $grade->grade = -1;
2649             $grade->grader = $USER->id;
2650             if ($attemptnumber >= 0) {
2651                 $grade->attemptnumber = $attemptnumber;
2652             }
2654             $gid = $DB->insert_record('assign_grades', $grade);
2655             $grade->id = $gid;
2656             return $grade;
2657         }
2658         return false;
2659     }
2661     /**
2662      * This will retrieve a grade object from the db.
2663      *
2664      * @param int $gradeid The id of the grade
2665      * @return stdClass The grade record
2666      */
2667     protected function get_grade($gradeid) {
2668         global $DB;
2670         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2671         return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2672     }
2674     /**
2675      * Print the grading page for a single user submission.
2676      *
2677      * @param moodleform $mform
2678      * @return string
2679      */
2680     protected function view_single_grade_page($mform) {
2681         global $DB, $CFG;
2683         $o = '';
2684         $instance = $this->get_instance();
2686         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2688         // Need submit permission to submit an assignment.
2689         require_capability('mod/assign:grade', $this->context);
2691         $header = new assign_header($instance,
2692                                     $this->get_context(),
2693                                     false,
2694                                     $this->get_course_module()->id,
2695                                     get_string('grading', 'assign'));
2696         $o .= $this->get_renderer()->render($header);
2698         // If userid is passed - we are only grading a single student.
2699         $rownum = required_param('rownum', PARAM_INT);
2700         $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2701         $userid = optional_param('userid', 0, PARAM_INT);
2702         $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2704         $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2705         if (!$userid) {
2706             if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2707                 $useridlist = $this->get_grading_userid_list();
2708             }
2709             $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2710         } else {
2711             $rownum = 0;
2712             $useridlist = array($userid);
2713         }
2715         if ($rownum < 0 || $rownum > count($useridlist)) {
2716             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2717         }
2719         $last = false;
2720         $userid = $useridlist[$rownum];
2721         if ($rownum == count($useridlist) - 1) {
2722             $last = true;
2723         }
2724         $user = $DB->get_record('user', array('id' => $userid));
2725         if ($user) {
2726             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2727             $usersummary = new assign_user_summary($user,
2728                                                    $this->get_course()->id,
2729                                                    $viewfullnames,
2730                                                    $this->is_blind_marking(),
2731                                                    $this->get_uniqueid_for_user($user->id),
2732                                                    get_extra_user_fields($this->get_context()),
2733                                                    !$this->is_active_user($userid));
2734             $o .= $this->get_renderer()->render($usersummary);
2735         }
2736         $submission = $this->get_user_submission($userid, false, $attemptnumber);
2737         $submissiongroup = null;
2738         $teamsubmission = null;
2739         $notsubmitted = array();
2740         if ($instance->teamsubmission) {
2741             $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2742             $submissiongroup = $this->get_submission_group($userid);
2743             $groupid = 0;
2744             if ($submissiongroup) {
2745                 $groupid = $submissiongroup->id;
2746             }
2747             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2749         }
2751         // Get the requested grade.
2752         $grade = $this->get_user_grade($userid, false, $attemptnumber);
2753         $flags = $this->get_user_flags($userid, false);
2754         if ($this->can_view_submission($userid)) {
2755             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2756             $extensionduedate = null;
2757             if ($flags) {
2758                 $extensionduedate = $flags->extensionduedate;
2759             }
2760             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2762             if ($teamsubmission) {
2763                 $showsubmit = $showedit &&
2764                               $teamsubmission &&
2765                               ($teamsubmission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) &&
2766                               !$this->submission_empty($teamsubmission);
2767             } else {
2768                 $showsubmit = $showedit &&
2769                               $submission &&
2770                               ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) &&
2771                               !$this->submission_empty($submission);
2772             }
2773             if (!$this->get_instance()->submissiondrafts) {
2774                 $showsubmit = false;
2775             }
2776             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2778             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2779                                                              $instance->alwaysshowdescription,
2780                                                              $submission,
2781                                                              $instance->teamsubmission,
2782                                                              $teamsubmission,
2783                                                              $submissiongroup,
2784                                                              $notsubmitted,
2785                                                              $this->is_any_submission_plugin_enabled(),
2786                                                              $gradelocked,
2787                                                              $this->is_graded($userid),
2788                                                              $instance->duedate,
2789                                                              $instance->cutoffdate,
2790                                                              $this->get_submission_plugins(),
2791                                                              $this->get_return_action(),
2792                                                              $this->get_return_params(),
2793                                                              $this->get_course_module()->id,
2794                                                              $this->get_course()->id,
2795                                                              assign_submission_status::GRADER_VIEW,
2796                                                              $showedit,
2797                                                              $showsubmit,
2798                                                              $viewfullnames,
2799                                                              $extensionduedate,
2800                                                              $this->get_context(),
2801                                                              $this->is_blind_marking(),
2802                                                              '',
2803                                                              $instance->attemptreopenmethod,
2804                                                              $instance->maxattempts);
2805             $o .= $this->get_renderer()->render($submissionstatus);
2806         }
2808         if ($grade) {
2809             $data = new stdClass();
2810             if ($grade->grade !== null && $grade->grade >= 0) {
2811                 $data->grade = format_float($grade->grade, 2);
2812             }
2813             if (!empty($flags->workflowstate)) {
2814                 $data->workflowstate = $flags->workflowstate;
2815             }
2816             if (!empty($flags->allocatedmarker)) {
2817                 $data->allocatedmarker = $flags->allocatedmarker;
2818             }
2819         } else {
2820             $data = new stdClass();
2821             $data->grade = '';
2822         }
2823         // Warning if required.
2824         $allsubmissions = $this->get_all_submissions($userid);
2826         if ($attemptnumber != -1) {
2827             $params = array('attemptnumber'=>$attemptnumber + 1,
2828                             'totalattempts'=>count($allsubmissions));
2829             $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2830             $o .= $this->get_renderer()->notification($message);
2831         }
2833         // Now show the grading form.
2834         if (!$mform) {
2835             $pagination = array('rownum'=>$rownum,
2836                                 'useridlistid'=>$useridlistid,
2837                                 'last'=>$last,
2838                                 'userid'=>optional_param('userid', 0, PARAM_INT),
2839                                 'attemptnumber'=>$attemptnumber);
2840             $formparams = array($this, $data, $pagination);
2841             $mform = new mod_assign_grade_form(null,
2842                                                $formparams,
2843                                                'post',
2844                                                '',
2845                                                array('class'=>'gradeform'));
2846         }
2847         $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2848         $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2850         if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2851             $allgrades = $this->get_all_grades($userid);
2852             $history = new assign_attempt_history($allsubmissions,
2853                                                   $allgrades,
2854                                                   $this->get_submission_plugins(),
2855                                                   $this->get_feedback_plugins(),
2856                                                   $this->get_course_module()->id,
2857                                                   $this->get_return_action(),
2858                                                   $this->get_return_params(),
2859                                                   true);
2861             $o .= $this->get_renderer()->render($history);
2862         }
2864         $msg = get_string('viewgradingformforstudent',
2865                           'assign',
2866                           array('id'=>$user->id, 'fullname'=>fullname($user)));
2867         $this->add_to_log('view grading form', $msg);
2869         $o .= $this->view_footer();
2870         return $o;
2871     }
2873     /**
2874      * Show a confirmation page to make sure they want to release student identities.
2875      *
2876      * @return string
2877      */
2878     protected function view_reveal_identities_confirm() {
2879         global $CFG, $USER;
2881         require_capability('mod/assign:revealidentities', $this->get_context());
2883         $o = '';
2884         $header = new assign_header($this->get_instance(),
2885                                     $this->get_context(),
2886                                     false,
2887                                     $this->get_course_module()->id);
2888         $o .= $this->get_renderer()->render($header);
2890         $urlparams = array('id'=>$this->get_course_module()->id,
2891                            'action'=>'revealidentitiesconfirm',
2892                            'sesskey'=>sesskey());
2893         $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2895         $urlparams = array('id'=>$this->get_course_module()->id,
2896                            'action'=>'grading');
2897         $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2899         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2900                                              $confirmurl,
2901                                              $cancelurl);
2902         $o .= $this->view_footer();
2903         $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2904         return $o;
2905     }
2907     /**
2908      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2909      *
2910      * @return string
2911      */
2912     protected function view_return_links() {
2913         $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2914         $returnparams = optional_param('returnparams', '', PARAM_TEXT);
2916         $params = array();
2917         $returnparams = str_replace('&amp;', '&', $returnparams);
2918         parse_str($returnparams, $params);
2919         $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2920         $params = array_merge($newparams, $params);
2922         $url = new moodle_url('/mod/assign/view.php', $params);
2923         return $this->get_renderer()->single_button($url, get_string('back'), 'get');
2924     }
2926     /**
2927      * View the grading table of all submissions for this assignment.
2928      *
2929      * @return string
2930      */
2931     protected function view_grading_table() {
2932         global $USER, $CFG;
2934         // Include grading options form.
2935         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2936         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2937         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2938         $o = '';
2939         $cmid = $this->get_course_module()->id;
2941         $links = array();
2942         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2943                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2944             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2945             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2946         }
2947         if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
2948             $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
2949             $links[$downloadurl] = get_string('downloadall', 'assign');
2950         }
2951         if ($this->is_blind_marking() &&
2952                 has_capability('mod/assign:revealidentities', $this->get_context())) {
2953             $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
2954             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2955         }
2956         foreach ($this->get_feedback_plugins() as $plugin) {
2957             if ($plugin->is_enabled() && $plugin->is_visible()) {
2958                 foreach ($plugin->get_grading_actions() as $action => $description) {
2959                     $url = '/mod/assign/view.php' .
2960                            '?id=' .  $cmid .
2961                            '&plugin=' . $plugin->get_type() .
2962                            '&pluginsubtype=assignfeedback' .
2963                            '&action=viewpluginpage&pluginaction=' . $action;
2964                     $links[$url] = $description;
2965                 }
2966             }
2967         }
2969         // Sort links alphabetically based on the link description.
2970         core_collator::asort($links);
2972         $gradingactions = new url_select($links);
2973         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2975         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2977         $perpage = get_user_preferences('assign_perpage', 10);
2978         $filter = get_user_preferences('assign_filter', '');
2979         $markerfilter = get_user_preferences('assign_markerfilter', '');
2980         $workflowfilter = get_user_preferences('assign_workflowfilter', '');
2981         $controller = $gradingmanager->get_active_controller();
2982         $showquickgrading = empty($controller);
2983         $quickgrading = get_user_preferences('assign_quickgrading', false);
2984         $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
2986         $markingallocation = $this->get_instance()->markingallocation &&
2987             has_capability('mod/assign:manageallocations', $this->context);
2988         // Get markers to use in drop lists.
2989         $markingallocationoptions = array();
2990         if ($markingallocation) {
2991             $markers = get_users_by_capability($this->context, 'mod/assign:grade');
2992             $markingallocationoptions[''] = get_string('filternone', 'assign');
2993             foreach ($markers as $marker) {
2994                 $markingallocationoptions[$marker->id] = fullname($marker);
2995             }
2996         }
2998         $markingworkflow = $this->get_instance()->markingworkflow;
2999         // Get marking states to show in form.
3000         $markingworkflowoptions = array();
3001         if ($markingworkflow) {
3002             $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
3003             $markingworkflowoptions[''] = get_string('filternone', 'assign');
3004             $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
3005             $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
3006         }
3008         // Print options for changing the filter and changing the number of results per page.
3009         $gradingoptionsformparams = array('cm'=>$cmid,
3010                                           'contextid'=>$this->context->id,
3011                                           'userid'=>$USER->id,
3012                                           'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
3013                                           'showquickgrading'=>$showquickgrading,
3014                                           'quickgrading'=>$quickgrading,
3015                                           'markingworkflowopt'=>$markingworkflowoptions,
3016                                           'markingallocationopt'=>$markingallocationoptions,
3017                                           'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
3018                                           'showonlyactiveenrol'=>$this->show_only_active_users());
3020         $classoptions = array('class'=>'gradingoptionsform');
3021         $gradingoptionsform = new mod_assign_grading_options_form(null,
3022                                                                   $gradingoptionsformparams,
3023                                                                   'post',
3024                                                                   '',
3025                                                                   $classoptions);
3027         $batchformparams = array('cm'=>$cmid,
3028                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3029                                  'duedate'=>$this->get_instance()->duedate,
3030                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3031                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3032                                  'context'=>$this->get_context(),
3033                                  'markingworkflow'=>$markingworkflow,
3034                                  'markingallocation'=>$markingallocation);
3035         $classoptions = array('class'=>'gradingbatchoperationsform');
3037         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
3038                                                                                    $batchformparams,
3039                                                                                    'post',
3040                                                                                    '',
3041                                                                                    $classoptions);
3043         $gradingoptionsdata = new stdClass();
3044         $gradingoptionsdata->perpage = $perpage;
3045         $gradingoptionsdata->filter = $filter;
3046         $gradingoptionsdata->markerfilter = $markerfilter;
3047         $gradingoptionsdata->workflowfilter = $workflowfilter;
3048         $gradingoptionsform->set_data($gradingoptionsdata);
3050         $actionformtext = $this->get_renderer()->render($gradingactions);
3051         $header = new assign_header($this->get_instance(),
3052                                     $this->get_context(),
3053                                     false,
3054                                     $this->get_course_module()->id,
3055                                     get_string('grading', 'assign'),
3056                                     $actionformtext);
3057         $o .= $this->get_renderer()->render($header);
3059         $currenturl = $CFG->wwwroot .
3060                       '/mod/assign/view.php?id=' .
3061                       $this->get_course_module()->id .
3062                       '&action=grading';
3064         $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3066         // Plagiarism update status apearring in the grading book.
3067         if (!empty($CFG->enableplagiarism)) {
3068             require_once($CFG->libdir . '/plagiarismlib.php');
3069             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
3070         }
3072         // Load and print the table of submissions.
3073         if ($showquickgrading && $quickgrading) {
3074             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3075             $table = $this->get_renderer()->render($gradingtable);
3076             $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
3077             $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3079             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3080         } else {
3081             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3082             $o .= $this->get_renderer()->render($gradingtable);
3083         }
3085         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3086         $users = array_keys($this->list_participants($currentgroup, true));
3087         if (count($users) != 0) {
3088             // If no enrolled user in a course then don't display the batch operations feature.
3089             $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3090             $o .= $this->get_renderer()->render($assignform);
3091         }
3092         $assignform = new assign_form('gradingoptionsform',
3093                                       $gradingoptionsform,
3094                                       'M.mod_assign.init_grading_options');
3095         $o .= $this->get_renderer()->render($assignform);
3096         return $o;
3097     }
3099     /**
3100      * View entire grading page.
3101      *
3102      * @return string
3103      */
3104     protected function view_grading_page() {
3105         global $CFG;
3107         $o = '';
3108         // Need submit permission to submit an assignment.
3109         require_capability('mod/assign:grade', $this->context);
3110         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3112         // Only load this if it is.
3114         $o .= $this->view_grading_table();
3116         $o .= $this->view_footer();
3118         $logmessage = get_string('viewsubmissiongradingtable', 'assign');
3119         $this->add_to_log('view submission grading table', $logmessage);
3120         return $o;
3121     }
3123     /**
3124      * Capture the output of the plagiarism plugins disclosures and return it as a string.
3125      *
3126      * @return void
3127      */
3128     protected function plagiarism_print_disclosure() {
3129         global $CFG;
3130         $o = '';
3132         if (!empty($CFG->enableplagiarism)) {
3133             require_once($CFG->libdir . '/plagiarismlib.php');
3135             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3136         }
3138         return $o;
3139     }
3141     /**
3142      * Message for students when assignment submissions have been closed.
3143      *
3144      * @return string
3145      */
3146     protected function view_student_error_message() {
3147         global $CFG;
3149         $o = '';
3150         // Need submit permission to submit an assignment.
3151         require_capability('mod/assign:submit', $this->context);
3153         $header = new assign_header($this->get_instance(),
3154                                     $this->get_context(),
3155                                     $this->show_intro(),
3156                                     $this->get_course_module()->id,
3157                                     get_string('editsubmission', 'assign'));
3158         $o .= $this->get_renderer()->render($header);
3160         $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
3162         $o .= $this->view_footer();
3164         return $o;
3166     }
3168     /**
3169      * View edit submissions page.
3170      *
3171      * @param moodleform $mform
3172      * @param array $notices A list of notices to display at the top of the
3173      *                       edit submission form (e.g. from plugins).
3174      * @return string The page output.
3175      */
3176     protected function view_edit_submission_page($mform, $notices) {
3177         global $CFG;
3179         $o = '';
3180         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
3181         // Need submit permission to submit an assignment.
3182         require_capability('mod/assign:submit', $this->context);
3184         if (!$this->submissions_open()) {
3185             return $this->view_student_error_message();
3186         }
3187         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3188                                                       $this->get_context(),
3189                                                       $this->show_intro(),
3190                                                       $this->get_course_module()->id,
3191                                                       get_string('editsubmission', 'assign')));
3192         $o .= $this->plagiarism_print_disclosure();
3193         $data = new stdClass();
3195         if (!$mform) {
3196             $mform = new mod_assign_submission_form(null, array($this, $data));
3197         }
3199         foreach ($notices as $notice) {
3200             $o .= $this->get_renderer()->notification($notice);
3201         }
3203         $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
3205         $o .= $this->view_footer();
3206         $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
3208         return $o;
3209     }
3211     /**
3212      * See if this assignment has a grade yet.
3213      *
3214      * @param int $userid
3215      * @return bool
3216      */
3217     protected function is_graded($userid) {
3218         $grade = $this->get_user_grade($userid, false);
3219         if ($grade) {
3220             return ($grade->grade !== null && $grade->grade >= 0);
3221         }
3222         return false;
3223     }
3225     /**
3226      * Perform an access check to see if the current $USER can view this group submission.
3227      *
3228      * @param int $groupid
3229      * @return bool
3230      */
3231     public function can_view_group_submission($groupid) {
3232         global $USER;
3234         if (!is_enrolled($this->get_course_context(), $USER->id)) {
3235             return false;
3236         }
3237         if (has_capability('mod/assign:grade', $this->context)) {
3238             return true;
3239         }
3240         $members = $this->get_submission_group_members($groupid, true);
3241         foreach ($members as $member) {
3242             if ($member->id == $USER->id) {
3243                 return true;
3244             }
3245         }
3246         return false;
3247     }
3249     /**
3250      * Perform an access check to see if the current $USER can view this users submission.
3251      *
3252      * @param int $userid
3253      * @return bool
3254      */
3255     public function can_view_submission($userid) {
3256         global $USER;
3258         if (is_siteadmin()) {
3259             return true;
3260         }
3261         if (!is_enrolled($this->get_course_context(), $userid)) {
3262             return false;