55cb0d57ca848f1a66e73ac0baa163a7d7001318
[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, $this->get_instance()->id);
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() && !$plugin->is_configurable() && $plugin->is_enabled()) {
971             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
972             $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
973             $mform->setType($name, PARAM_BOOL);
974             $plugin->get_settings($mform);
975         } else if ($plugin->is_visible() && $plugin->is_configurable()) {
976             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
977             $label = $plugin->get_name();
978             $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
979             $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
981             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
982             if ($plugin->get_config('enabled') !== false) {
983                 $default = $plugin->is_enabled();
984             }
985             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
987             $plugin->get_settings($mform);
989         }
990     }
992     /**
993      * Add settings to edit plugin form.
994      *
995      * @param MoodleQuickForm $mform The form to add the configuration settings to.
996      *                               This form is modified directly (not returned).
997      * @return void
998      */
999     public function add_all_plugin_settings(MoodleQuickForm $mform) {
1000         $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
1002         $submissionpluginsenabled = array();
1003         $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1004         foreach ($this->submissionplugins as $plugin) {
1005             $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1006         }
1007         $group->setElements($submissionpluginsenabled);
1009         $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1010         $feedbackpluginsenabled = array();
1011         $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1012         foreach ($this->feedbackplugins as $plugin) {
1013             $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1014         }
1015         $group->setElements($feedbackpluginsenabled);
1016         $mform->setExpanded('submissiontypes');
1017     }
1019     /**
1020      * Allow each plugin an opportunity to update the defaultvalues
1021      * passed in to the settings form (needed to set up draft areas for
1022      * editor and filemanager elements)
1023      *
1024      * @param array $defaultvalues
1025      */
1026     public function plugin_data_preprocessing(&$defaultvalues) {
1027         foreach ($this->submissionplugins as $plugin) {
1028             if ($plugin->is_visible()) {
1029                 $plugin->data_preprocessing($defaultvalues);
1030             }
1031         }
1032         foreach ($this->feedbackplugins as $plugin) {
1033             if ($plugin->is_visible()) {
1034                 $plugin->data_preprocessing($defaultvalues);
1035             }
1036         }
1037     }
1039     /**
1040      * Get the name of the current module.
1041      *
1042      * @return string the module name (Assignment)
1043      */
1044     protected function get_module_name() {
1045         if (isset(self::$modulename)) {
1046             return self::$modulename;
1047         }
1048         self::$modulename = get_string('modulename', 'assign');
1049         return self::$modulename;
1050     }
1052     /**
1053      * Get the plural name of the current module.
1054      *
1055      * @return string the module name plural (Assignments)
1056      */
1057     protected function get_module_name_plural() {
1058         if (isset(self::$modulenameplural)) {
1059             return self::$modulenameplural;
1060         }
1061         self::$modulenameplural = get_string('modulenameplural', 'assign');
1062         return self::$modulenameplural;
1063     }
1065     /**
1066      * Has this assignment been constructed from an instance?
1067      *
1068      * @return bool
1069      */
1070     public function has_instance() {
1071         return $this->instance || $this->get_course_module();
1072     }
1074     /**
1075      * Get the settings for the current instance of this assignment
1076      *
1077      * @return stdClass The settings
1078      */
1079     public function get_instance() {
1080         global $DB;
1081         if ($this->instance) {
1082             return $this->instance;
1083         }
1084         if ($this->get_course_module()) {
1085             $params = array('id' => $this->get_course_module()->instance);
1086             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1087         }
1088         if (!$this->instance) {
1089             throw new coding_exception('Improper use of the assignment class. ' .
1090                                        'Cannot load the assignment record.');
1091         }
1092         return $this->instance;
1093     }
1095     /**
1096      * Get the primary grade item for this assign instance.
1097      *
1098      * @return stdClass The grade_item record
1099      */
1100     public function get_grade_item() {
1101         if ($this->gradeitem) {
1102             return $this->gradeitem;
1103         }
1104         $instance = $this->get_instance();
1105         $params = array('itemtype' => 'mod',
1106                         'itemmodule' => 'assign',
1107                         'iteminstance' => $instance->id,
1108                         'courseid' => $instance->course,
1109                         'itemnumber' => 0);
1110         $this->gradeitem = grade_item::fetch($params);
1111         if (!$this->gradeitem) {
1112             throw new coding_exception('Improper use of the assignment class. ' .
1113                                        'Cannot load the grade item.');
1114         }
1115         return $this->gradeitem;
1116     }
1118     /**
1119      * Get the context of the current course.
1120      *
1121      * @return mixed context|null The course context
1122      */
1123     public function get_course_context() {
1124         if (!$this->context && !$this->course) {
1125             throw new coding_exception('Improper use of the assignment class. ' .
1126                                        'Cannot load the course context.');
1127         }
1128         if ($this->context) {
1129             return $this->context->get_course_context();
1130         } else {
1131             return context_course::instance($this->course->id);
1132         }
1133     }
1136     /**
1137      * Get the current course module.
1138      *
1139      * @return mixed stdClass|null The course module
1140      */
1141     public function get_course_module() {
1142         if ($this->coursemodule) {
1143             return $this->coursemodule;
1144         }
1145         if (!$this->context) {
1146             return null;
1147         }
1149         if ($this->context->contextlevel == CONTEXT_MODULE) {
1150             $this->coursemodule = get_coursemodule_from_id('assign',
1151                                                            $this->context->instanceid,
1152                                                            0,
1153                                                            false,
1154                                                            MUST_EXIST);
1155             return $this->coursemodule;
1156         }
1157         return null;
1158     }
1160     /**
1161      * Get context module.
1162      *
1163      * @return context
1164      */
1165     public function get_context() {
1166         return $this->context;
1167     }
1169     /**
1170      * Get the current course.
1171      *
1172      * @return mixed stdClass|null The course
1173      */
1174     public function get_course() {
1175         global $DB;
1177         if ($this->course) {
1178             return $this->course;
1179         }
1181         if (!$this->context) {
1182             return null;
1183         }
1184         $params = array('id' => $this->get_course_context()->instanceid);
1185         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1187         return $this->course;
1188     }
1190     /**
1191      * Return a grade in user-friendly form, whether it's a scale or not.
1192      *
1193      * @param mixed $grade int|null
1194      * @param boolean $editing Are we allowing changes to this grade?
1195      * @param int $userid The user id the grade belongs to
1196      * @param int $modified Timestamp from when the grade was last modified
1197      * @return string User-friendly representation of grade
1198      */
1199     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1200         global $DB;
1202         static $scalegrades = array();
1204         $o = '';
1206         if ($this->get_instance()->grade >= 0) {
1207             // Normal number.
1208             if ($editing && $this->get_instance()->grade > 0) {
1209                 if ($grade < 0) {
1210                     $displaygrade = '';
1211                 } else {
1212                     $displaygrade = format_float($grade, 2);
1213                 }
1214                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1215                        get_string('usergrade', 'assign') .
1216                        '</label>';
1217                 $o .= '<input type="text"
1218                               id="quickgrade_' . $userid . '"
1219                               name="quickgrade_' . $userid . '"
1220                               value="' .  $displaygrade . '"
1221                               size="6"
1222                               maxlength="10"
1223                               class="quickgrade"/>';
1224                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1225                 $o .= '<input type="hidden"
1226                               name="grademodified_' . $userid . '"
1227                               value="' . $modified . '"/>';
1228                 return $o;
1229             } else {
1230                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1231                 if ($grade == -1 || $grade === null) {
1232                     $o .= '-';
1233                 } else {
1234                     $item = $this->get_grade_item();
1235                     $o .= grade_format_gradevalue($grade, $item);
1236                     if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1237                         // If displaying the raw grade, also display the total value.
1238                         $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1239                     }
1240                 }
1241                 return $o;
1242             }
1244         } else {
1245             // Scale.
1246             if (empty($this->cache['scale'])) {
1247                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1248                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1249                 } else {
1250                     $o .= '-';
1251                     return $o;
1252                 }
1253             }
1254             if ($editing) {
1255                 $o .= '<label class="accesshide"
1256                               for="quickgrade_' . $userid . '">' .
1257                       get_string('usergrade', 'assign') .
1258                       '</label>';
1259                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1260                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1261                 foreach ($this->cache['scale'] as $optionid => $option) {
1262                     $selected = '';
1263                     if ($grade == $optionid) {
1264                         $selected = 'selected="selected"';
1265                     }
1266                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1267                 }
1268                 $o .= '</select>';
1269                 $o .= '<input type="hidden" ' .
1270                              'name="grademodified_' . $userid . '" ' .
1271                              'value="' . $modified . '"/>';
1272                 return $o;
1273             } else {
1274                 $scaleid = (int)$grade;
1275                 if (isset($this->cache['scale'][$scaleid])) {
1276                     $o .= $this->cache['scale'][$scaleid];
1277                     return $o;
1278                 }
1279                 $o .= '-';
1280                 return $o;
1281             }
1282         }
1283     }
1285     /**
1286      * Load a list of users enrolled in the current course with the specified permission and group.
1287      * 0 for no group.
1288      *
1289      * @param int $currentgroup
1290      * @param bool $idsonly
1291      * @return array List of user records
1292      */
1293     public function list_participants($currentgroup, $idsonly) {
1294         if ($idsonly) {
1295             $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.id', null, null, null,
1296                     $this->show_only_active_users());
1297         } else {
1298             $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', null, null, null,
1299                     $this->show_only_active_users());
1300         }
1302         $cm = $this->get_course_module();
1303         foreach ($users as $userid => $user) {
1304             if (!groups_course_module_visible($cm, $userid)) {
1305                 unset($users[$userid]);
1306             }
1307         }
1309         return $users;
1310     }
1312     /**
1313      * Load a count of valid teams for this assignment.
1314      *
1315      * @return int number of valid teams
1316      */
1317     public function count_teams() {
1319         $groups = groups_get_all_groups($this->get_course()->id,
1320                                         0,
1321                                         $this->get_instance()->teamsubmissiongroupingid,
1322                                         'g.id');
1323         $count = count($groups);
1325         // See if there are any users in the default group.
1326         $defaultusers = $this->get_submission_group_members(0, true);
1327         if (count($defaultusers) > 0) {
1328             $count += 1;
1329         }
1330         return $count;
1331     }
1333     /**
1334      * Load a count of active users enrolled in the current course with the specified permission and group.
1335      * 0 for no group.
1336      *
1337      * @param int $currentgroup
1338      * @return int number of matching users
1339      */
1340     public function count_participants($currentgroup) {
1341         return count($this->list_participants($currentgroup, true));
1342     }
1344     /**
1345      * Load a count of active users submissions in the current module that require grading
1346      * This means the submission modification time is more recent than the
1347      * grading modification time and the status is SUBMITTED.
1348      *
1349      * @return int number of matching submissions
1350      */
1351     public function count_submissions_need_grading() {
1352         global $DB;
1354         if ($this->get_instance()->teamsubmission) {
1355             // This does not make sense for group assignment because the submission is shared.
1356             return 0;
1357         }
1359         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1360         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1362         $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1363                                  FROM {assign_submission} mxs
1364                                  WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1365         $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1366                             FROM {assign_grades} mxg
1367                             WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1369         $params['assignid'] = $this->get_instance()->id;
1370         $params['assignid2'] = $this->get_instance()->id;
1371         $params['assignid3'] = $this->get_instance()->id;
1372         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1374         $sql = 'SELECT COUNT(s.userid)
1375                    FROM {assign_submission} s
1376                    LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1377                    LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1378                    LEFT JOIN {assign_grades} g ON
1379                         s.assignment = g.assignment AND
1380                         s.userid = g.userid AND
1381                         g.attemptnumber = gmx.maxattempt
1382                    JOIN(' . $esql . ') e ON e.id = s.userid
1383                    WHERE
1384                         s.attemptnumber = smx.maxattempt AND
1385                         s.assignment = :assignid AND
1386                         s.timemodified IS NOT NULL AND
1387                         s.status = :submitted AND
1388                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1390         return $DB->count_records_sql($sql, $params);
1391     }
1393     /**
1394      * Load a count of grades.
1395      *
1396      * @return int number of grades
1397      */
1398     public function count_grades() {
1399         global $DB;
1401         if (!$this->has_instance()) {
1402             return 0;
1403         }
1405         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1406         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1408         $params['assignid'] = $this->get_instance()->id;
1410         $sql = 'SELECT COUNT(g.userid)
1411                    FROM {assign_grades} g
1412                    JOIN(' . $esql . ') e ON e.id = g.userid
1413                    WHERE g.assignment = :assignid';
1415         return $DB->count_records_sql($sql, $params);
1416     }
1418     /**
1419      * Load a count of submissions.
1420      *
1421      * @return int number of submissions
1422      */
1423     public function count_submissions() {
1424         global $DB;
1426         if (!$this->has_instance()) {
1427             return 0;
1428         }
1430         $params = array();
1432         if ($this->get_instance()->teamsubmission) {
1433             // We cannot join on the enrolment tables for group submissions (no userid).
1434             $sql = 'SELECT COUNT(DISTINCT s.groupid)
1435                         FROM {assign_submission} s
1436                         WHERE
1437                             s.assignment = :assignid AND
1438                             s.timemodified IS NOT NULL AND
1439                             s.userid = :groupuserid';
1441             $params['assignid'] = $this->get_instance()->id;
1442             $params['groupuserid'] = 0;
1443         } else {
1444             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1445             list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1447             $params['assignid'] = $this->get_instance()->id;
1449             $sql = 'SELECT COUNT(DISTINCT s.userid)
1450                        FROM {assign_submission} s
1451                        JOIN(' . $esql . ') e ON e.id = s.userid
1452                        WHERE
1453                             s.assignment = :assignid AND
1454                             s.timemodified IS NOT NULL';
1456         }
1458         return $DB->count_records_sql($sql, $params);
1459     }
1461     /**
1462      * Load a count of submissions with a specified status.
1463      *
1464      * @param string $status The submission status - should match one of the constants
1465      * @return int number of matching submissions
1466      */
1467     public function count_submissions_with_status($status) {
1468         global $DB;
1470         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1471         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1473         $params['assignid'] = $this->get_instance()->id;
1474         $params['assignid2'] = $this->get_instance()->id;
1475         $params['submissionstatus'] = $status;
1477         if ($this->get_instance()->teamsubmission) {
1478             $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1479                               FROM {assign_submission} mxs
1480                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1482             $sql = 'SELECT COUNT(s.groupid)
1483                         FROM {assign_submission} s
1484                         JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1485                         WHERE
1486                             s.attemptnumber = smx.maxattempt AND
1487                             s.assignment = :assignid AND
1488                             s.timemodified IS NOT NULL AND
1489                             s.userid = :groupuserid AND
1490                             s.status = :submissionstatus';
1491             $params['groupuserid'] = 0;
1492         } else {
1493             $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1494                               FROM {assign_submission} mxs
1495                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1497             $sql = 'SELECT COUNT(s.userid)
1498                         FROM {assign_submission} s
1499                         JOIN(' . $esql . ') e ON e.id = s.userid
1500                         JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1501                         WHERE
1502                             s.attemptnumber = smx.maxattempt AND
1503                             s.assignment = :assignid AND
1504                             s.timemodified IS NOT NULL AND
1505                             s.status = :submissionstatus';
1507         }
1509         return $DB->count_records_sql($sql, $params);
1510     }
1512     /**
1513      * Utility function to get the userid for every row in the grading table
1514      * so the order can be frozen while we iterate it.
1515      *
1516      * @return array An array of userids
1517      */
1518     protected function get_grading_userid_list() {
1519         $filter = get_user_preferences('assign_filter', '');
1520         $table = new assign_grading_table($this, 0, $filter, 0, false);
1522         $useridlist = $table->get_column_data('userid');
1524         return $useridlist;
1525     }
1527     /**
1528      * Generate zip file from array of given files.
1529      *
1530      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1531      *                                 This array is indexed by the final file name and each
1532      *                                 element in the array is an instance of a stored_file object.
1533      * @return path of temp file - note this returned file does
1534      *         not have a .zip extension - it is a temp file.
1535      */
1536     protected function pack_files($filesforzipping) {
1537         global $CFG;
1538         // Create path for new zip file.
1539         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1540         // Zip files.
1541         $zipper = new zip_packer();
1542         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1543             return $tempzip;
1544         }
1545         return false;
1546     }
1548     /**
1549      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1550      *
1551      * Cron function to be run periodically according to the moodle cron.
1552      *
1553      * @return bool
1554      */
1555     public static function cron() {
1556         global $DB;
1558         // Only ever send a max of one days worth of updates.
1559         $yesterday = time() - (24 * 3600);
1560         $timenow   = time();
1562         // Collect all submissions from the past 24 hours that require mailing.
1563         $sql = 'SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
1564                        g.*, g.timemodified as lastmodified
1565                  FROM {assign} a
1566                  JOIN {assign_grades} g ON g.assignment = a.id
1567                  LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1568                 WHERE g.timemodified >= :yesterday AND
1569                       g.timemodified <= :today AND
1570                       uf.mailed = 0';
1572         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1573         $submissions = $DB->get_records_sql($sql, $params);
1575         if (empty($submissions)) {
1576             return true;
1577         }
1579         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1581         // Preload courses we are going to need those.
1582         $courseids = array();
1583         foreach ($submissions as $submission) {
1584             $courseids[] = $submission->course;
1585         }
1587         // Filter out duplicates.
1588         $courseids = array_unique($courseids);
1589         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1590         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1591         $sql = 'SELECT c.*, ' . $ctxselect .
1592                   ' FROM {course} c
1593              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1594                  WHERE c.id ' . $courseidsql;
1596         $params['contextlevel'] = CONTEXT_COURSE;
1597         $courses = $DB->get_records_sql($sql, $params);
1599         // Clean up... this could go on for a while.
1600         unset($courseids);
1601         unset($ctxselect);
1602         unset($courseidsql);
1603         unset($params);
1605         // Simple array we'll use for caching modules.
1606         $modcache = array();
1608         // Message students about new feedback.
1609         foreach ($submissions as $submission) {
1611             mtrace("Processing assignment submission $submission->id ...");
1613             // Do not cache user lookups - could be too many.
1614             if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1615                 mtrace('Could not find user ' . $submission->userid);
1616                 continue;
1617             }
1619             // Use a cache to prevent the same DB queries happening over and over.
1620             if (!array_key_exists($submission->course, $courses)) {
1621                 mtrace('Could not find course ' . $submission->course);
1622                 continue;
1623             }
1624             $course = $courses[$submission->course];
1625             if (isset($course->ctxid)) {
1626                 // Context has not yet been preloaded. Do so now.
1627                 context_helper::preload_from_record($course);
1628             }
1630             // Override the language and timezone of the "current" user, so that
1631             // mail is customised for the receiver.
1632             cron_setup_user($user, $course);
1634             // Context lookups are already cached.
1635             $coursecontext = context_course::instance($course->id);
1636             if (!is_enrolled($coursecontext, $user->id)) {
1637                 $courseshortname = format_string($course->shortname,
1638                                                  true,
1639                                                  array('context' => $coursecontext));
1640                 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1641                 continue;
1642             }
1644             if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1645                 mtrace('Could not find grader ' . $submission->grader);
1646                 continue;
1647             }
1649             if (!array_key_exists($submission->assignment, $modcache)) {
1650                 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1651                 if (empty($mod)) {
1652                     mtrace('Could not find course module for assignment id ' . $submission->assignment);
1653                     continue;
1654                 }
1655                 $modcache[$submission->assignment] = $mod;
1656             } else {
1657                 $mod = $modcache[$submission->assignment];
1658             }
1659             // Context lookups are already cached.
1660             $contextmodule = context_module::instance($mod->id);
1662             if (!$mod->visible) {
1663                 // Hold mail notification for hidden assignments until later.
1664                 continue;
1665             }
1667             // Need to send this to the student.
1668             $messagetype = 'feedbackavailable';
1669             $eventtype = 'assign_notification';
1670             $updatetime = $submission->lastmodified;
1671             $modulename = get_string('modulename', 'assign');
1673             $uniqueid = 0;
1674             if ($submission->blindmarking && !$submission->revealidentities) {
1675                 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1676             }
1677             $showusers = $submission->blindmarking && !$submission->revealidentities;
1678             self::send_assignment_notification($grader,
1679                                                $user,
1680                                                $messagetype,
1681                                                $eventtype,
1682                                                $updatetime,
1683                                                $mod,
1684                                                $contextmodule,
1685                                                $course,
1686                                                $modulename,
1687                                                $submission->name,
1688                                                $showusers,
1689                                                $uniqueid);
1691             $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1692             if ($flags) {
1693                 $flags->mailed = 1;
1694                 $DB->update_record('assign_user_flags', $flags);
1695             } else {
1696                 $flags = new stdClass();
1697                 $flags->userid = $user->id;
1698                 $flags->assignment = $submission->assignment;
1699                 $flags->mailed = 1;
1700                 $DB->insert_record('assign_user_flags', $flags);
1701             }
1703             mtrace('Done');
1704         }
1705         mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1707         cron_setup_user();
1709         // Free up memory just to be sure.
1710         unset($courses);
1711         unset($modcache);
1713         return true;
1714     }
1716     /**
1717      * Mark in the database that this grade record should have an update notification sent by cron.
1718      *
1719      * @param stdClass $grade a grade record keyed on id
1720      * @return bool true for success
1721      */
1722     public function notify_grade_modified($grade) {
1723         global $DB;
1725         $flags = $this->get_user_flags($grade->userid, true);
1726         if ($flags->mailed != 1) {
1727             $flags->mailed = 0;
1728         }
1730         return $this->update_user_flags($flags);
1731     }
1733     /**
1734      * Update user flags for this user in this assignment.
1735      *
1736      * @param stdClass $flags a flags record keyed on id
1737      * @return bool true for success
1738      */
1739     public function update_user_flags($flags) {
1740         global $DB;
1741         if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1742             return false;
1743         }
1745         $result = $DB->update_record('assign_user_flags', $flags);
1746         return $result;
1747     }
1749     /**
1750      * Update a grade in the grade table for the assignment and in the gradebook.
1751      *
1752      * @param stdClass $grade a grade record keyed on id
1753      * @return bool true for success
1754      */
1755     public function update_grade($grade) {
1756         global $DB;
1758         $grade->timemodified = time();
1760         if (!empty($grade->workflowstate)) {
1761             $validstates = $this->get_marking_workflow_states_for_current_user();
1762             if (!array_key_exists($grade->workflowstate, $validstates)) {
1763                 return false;
1764             }
1765         }
1767         if ($grade->grade && $grade->grade != -1) {
1768             if ($this->get_instance()->grade > 0) {
1769                 if (!is_numeric($grade->grade)) {
1770                     return false;
1771                 } else if ($grade->grade > $this->get_instance()->grade) {
1772                     return false;
1773                 } else if ($grade->grade < 0) {
1774                     return false;
1775                 }
1776             } else {
1777                 // This is a scale.
1778                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1779                     $scaleoptions = make_menu_from_list($scale->scale);
1780                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1781                         return false;
1782                     }
1783                 }
1784             }
1785         }
1787         if (empty($grade->attemptnumber)) {
1788             // Set it to the default.
1789             $grade->attemptnumber = 0;
1790         }
1791         $result = $DB->update_record('assign_grades', $grade);
1793         // Only push to gradebook if the update is for the latest attempt.
1794         $submission = null;
1795         if ($this->get_instance()->teamsubmission) {
1796             $submission = $this->get_group_submission($grade->userid, 0, false);
1797         } else {
1798             $submission = $this->get_user_submission($grade->userid, false);
1799         }
1800         // Not the latest attempt.
1801         if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1802             return true;
1803         }
1805         if ($result) {
1806             $this->gradebook_item_update(null, $grade);
1807         }
1808         return $result;
1809     }
1811     /**
1812      * View the grant extension date page.
1813      *
1814      * Uses url parameters 'userid'
1815      * or from parameter 'selectedusers'
1816      *
1817      * @param moodleform $mform - Used for validation of the submitted data
1818      * @return string
1819      */
1820     protected function view_grant_extension($mform) {
1821         global $DB, $CFG;
1822         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1824         $o = '';
1825         $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1826         $data = new stdClass();
1827         $data->extensionduedate = null;
1828         $userid = 0;
1829         if (!$batchusers) {
1830             $userid = required_param('userid', PARAM_INT);
1832             $grade = $this->get_user_grade($userid, false);
1834             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1836             if ($grade) {
1837                 $data->extensionduedate = $grade->extensionduedate;
1838             }
1839             $data->userid = $userid;
1840         } else {
1841             $data->batchusers = $batchusers;
1842         }
1843         $header = new assign_header($this->get_instance(),
1844                                     $this->get_context(),
1845                                     $this->show_intro(),
1846                                     $this->get_course_module()->id,
1847                                     get_string('grantextension', 'assign'));
1848         $o .= $this->get_renderer()->render($header);
1850         if (!$mform) {
1851             $formparams = array($this->get_course_module()->id,
1852                                 $userid,
1853                                 $batchusers,
1854                                 $this->get_instance(),
1855                                 $data);
1856             $mform = new mod_assign_extension_form(null, $formparams);
1857         }
1858         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1859         $o .= $this->view_footer();
1860         return $o;
1861     }
1863     /**
1864      * Get a list of the users in the same group as this user.
1865      *
1866      * @param int $groupid The id of the group whose members we want or 0 for the default group
1867      * @param bool $onlyids Whether to retrieve only the user id's
1868      * @return array The users (possibly id's only)
1869      */
1870     public function get_submission_group_members($groupid, $onlyids) {
1871         $members = array();
1872         if ($groupid != 0) {
1873             if ($onlyids) {
1874                 $allusers = groups_get_members($groupid, 'u.id');
1875             } else {
1876                 $allusers = groups_get_members($groupid);
1877             }
1878             foreach ($allusers as $user) {
1879                 if ($this->get_submission_group($user->id)) {
1880                     $members[] = $user;
1881                 }
1882             }
1883         } else {
1884             $allusers = $this->list_participants(null, $onlyids);
1885             foreach ($allusers as $user) {
1886                 if ($this->get_submission_group($user->id) == null) {
1887                     $members[] = $user;
1888                 }
1889             }
1890         }
1891         // Exclude suspended users, if user can't see them.
1892         if (!has_capability('moodle/course:viewsuspendedusers', $this->context)) {
1893             foreach ($members as $key => $member) {
1894                 if (!$this->is_active_user($member->id)) {
1895                     unset($members[$key]);
1896                 }
1897             }
1898         }
1899         return $members;
1900     }
1902     /**
1903      * Get a list of the users in the same group as this user that have not submitted the assignment.
1904      *
1905      * @param int $groupid The id of the group whose members we want or 0 for the default group
1906      * @param bool $onlyids Whether to retrieve only the user id's
1907      * @return array The users (possibly id's only)
1908      */
1909     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1910         $instance = $this->get_instance();
1911         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1912             return array();
1913         }
1914         $members = $this->get_submission_group_members($groupid, $onlyids);
1916         foreach ($members as $id => $member) {
1917             $submission = $this->get_user_submission($member->id, false);
1918             if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1919                 unset($members[$id]);
1920             } else {
1921                 if ($this->is_blind_marking()) {
1922                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
1923                                            $this->get_uniqueid_for_user($id);
1924                 }
1925             }
1926         }
1927         return $members;
1928     }
1930     /**
1931      * Load the group submission object for a particular user, optionally creating it if required.
1932      *
1933      * @param int $userid The id of the user whose submission we want
1934      * @param int $groupid The id of the group for this user - may be 0 in which
1935      *                     case it is determined from the userid.
1936      * @param bool $create If set to true a new submission object will be created in the database
1937      * @param int $attemptnumber - -1 means the latest attempt
1938      * @return stdClass The submission
1939      */
1940     public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
1941         global $DB;
1943         if ($groupid == 0) {
1944             $group = $this->get_submission_group($userid);
1945             if ($group) {
1946                 $groupid = $group->id;
1947             }
1948         }
1950         // Now get the group submission.
1951         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1952         if ($attemptnumber >= 0) {
1953             $params['attemptnumber'] = $attemptnumber;
1954         }
1956         // Only return the row with the highest attemptnumber.
1957         $submission = null;
1958         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
1959         if ($submissions) {
1960             $submission = reset($submissions);
1961         }
1963         if ($submission) {
1964             return $submission;
1965         }
1966         if ($create) {
1967             $submission = new stdClass();
1968             $submission->assignment = $this->get_instance()->id;
1969             $submission->userid = 0;
1970             $submission->groupid = $groupid;
1971             $submission->timecreated = time();
1972             $submission->timemodified = $submission->timecreated;
1973             if ($attemptnumber >= 0) {
1974                 $submission->attemptnumber = $attemptnumber;
1975             } else {
1976                 $submission->attemptnumber = 0;
1977             }
1979             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1980             $sid = $DB->insert_record('assign_submission', $submission);
1981             $submission->id = $sid;
1982             return $submission;
1983         }
1984         return false;
1985     }
1987     /**
1988      * View a summary listing of all assignments in the current course.
1989      *
1990      * @return string
1991      */
1992     private function view_course_index() {
1993         global $USER;
1995         $o = '';
1997         $course = $this->get_course();
1998         $strplural = get_string('modulenameplural', 'assign');
2000         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2001             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2002             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2003             return $o;
2004         }
2006         $strsectionname = '';
2007         $usesections = course_format_uses_sections($course->format);
2008         $modinfo = get_fast_modinfo($course);
2010         if ($usesections) {
2011             $strsectionname = get_string('sectionname', 'format_'.$course->format);
2012             $sections = $modinfo->get_section_info_all();
2013         }
2014         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2016         $timenow = time();
2018         $currentsection = '';
2019         foreach ($modinfo->instances['assign'] as $cm) {
2020             if (!$cm->uservisible) {
2021                 continue;
2022             }
2024             $timedue = $cms[$cm->id]->duedate;
2026             $sectionname = '';
2027             if ($usesections && $cm->sectionnum) {
2028                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2029             }
2031             $submitted = '';
2032             $context = context_module::instance($cm->id);
2034             $assignment = new assign($context, $cm, $course);
2036             if (has_capability('mod/assign:grade', $context)) {
2037                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2039             } else if (has_capability('mod/assign:submit', $context)) {
2040                 $usersubmission = $assignment->get_user_submission($USER->id, false);
2042                 if (!empty($usersubmission->status)) {
2043                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2044                 } else {
2045                     $submitted = get_string('submissionstatus_', 'assign');
2046                 }
2047             }
2048             $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2049             if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2050                     !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2051                 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2052             } else {
2053                 $grade = '-';
2054             }
2056             $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2058         }
2060         $o .= $this->get_renderer()->render($courseindexsummary);
2061         $o .= $this->view_footer();
2063         return $o;
2064     }
2066     /**
2067      * View a page rendered by a plugin.
2068      *
2069      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2070      *
2071      * @return string
2072      */
2073     protected function view_plugin_page() {
2074         global $USER;
2076         $o = '';
2078         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2079         $plugintype = required_param('plugin', PARAM_TEXT);
2080         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2082         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2083         if (!$plugin) {
2084             print_error('invalidformdata', '');
2085             return;
2086         }
2088         $o .= $plugin->view_page($pluginaction);
2090         return $o;
2091     }
2094     /**
2095      * This is used for team assignments to get the group for the specified user.
2096      * If the user is a member of multiple or no groups this will return false
2097      *
2098      * @param int $userid The id of the user whose submission we want
2099      * @return mixed The group or false
2100      */
2101     public function get_submission_group($userid) {
2102         $grouping = $this->get_instance()->teamsubmissiongroupingid;
2103         $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2104         if (count($groups) != 1) {
2105             return false;
2106         }
2107         return array_pop($groups);
2108     }
2111     /**
2112      * Display the submission that is used by a plugin.
2113      *
2114      * Uses url parameters 'sid', 'gid' and 'plugin'.
2115      *
2116      * @param string $pluginsubtype
2117      * @return string
2118      */
2119     protected function view_plugin_content($pluginsubtype) {
2120         global $USER;
2122         $o = '';
2124         $submissionid = optional_param('sid', 0, PARAM_INT);
2125         $gradeid = optional_param('gid', 0, PARAM_INT);
2126         $plugintype = required_param('plugin', PARAM_TEXT);
2127         $item = null;
2128         if ($pluginsubtype == 'assignsubmission') {
2129             $plugin = $this->get_submission_plugin_by_type($plugintype);
2130             if ($submissionid <= 0) {
2131                 throw new coding_exception('Submission id should not be 0');
2132             }
2133             $item = $this->get_submission($submissionid);
2135             // Check permissions.
2136             if ($item->userid != $USER->id) {
2137                 require_capability('mod/assign:grade', $this->context);
2138             }
2139             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2140                                                               $this->get_context(),
2141                                                               $this->show_intro(),
2142                                                               $this->get_course_module()->id,
2143                                                               $plugin->get_name()));
2144             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2145                                                               $item,
2146                                                               assign_submission_plugin_submission::FULL,
2147                                                               $this->get_course_module()->id,
2148                                                               $this->get_return_action(),
2149                                                               $this->get_return_params()));
2151             $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
2152             $this->add_to_log('view submission', $logmessage);
2153         } else {
2154             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2155             if ($gradeid <= 0) {
2156                 throw new coding_exception('Grade id should not be 0');
2157             }
2158             $item = $this->get_grade($gradeid);
2159             // Check permissions.
2160             if ($item->userid != $USER->id) {
2161                 require_capability('mod/assign:grade', $this->context);
2162             }
2163             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2164                                                               $this->get_context(),
2165                                                               $this->show_intro(),
2166                                                               $this->get_course_module()->id,
2167                                                               $plugin->get_name()));
2168             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2169                                                               $item,
2170                                                               assign_feedback_plugin_feedback::FULL,
2171                                                               $this->get_course_module()->id,
2172                                                               $this->get_return_action(),
2173                                                               $this->get_return_params()));
2174             $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
2175             $this->add_to_log('view feedback', $logmessage);
2176         }
2178         $o .= $this->view_return_links();
2180         $o .= $this->view_footer();
2181         return $o;
2182     }
2184     /**
2185      * Rewrite plugin file urls so they resolve correctly in an exported zip.
2186      *
2187      * @param string $text - The replacement text
2188      * @param stdClass $user - The user record
2189      * @param assign_plugin $plugin - The assignment plugin
2190      */
2191     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2192         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2193         $groupname = '';
2194         if ($groupmode) {
2195             $groupid = groups_get_activity_group($this->get_course_module(), true);
2196             $groupname = groups_get_group_name($groupid).'-';
2197         }
2199         if ($this->is_blind_marking()) {
2200             $prefix = $groupname . get_string('participant', 'assign');
2201             $prefix = str_replace('_', ' ', $prefix);
2202             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2203         } else {
2204             $prefix = $groupname . fullname($user);
2205             $prefix = str_replace('_', ' ', $prefix);
2206             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2207         }
2209         $subtype = $plugin->get_subtype();
2210         $type = $plugin->get_type();
2211         $prefix = $prefix . $subtype . '_' . $type . '_';
2213         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2215         return $result;
2216     }
2218     /**
2219      * Render the content in editor that is often used by plugin.
2220      *
2221      * @param string $filearea
2222      * @param int  $submissionid
2223      * @param string $plugintype
2224      * @param string $editor
2225      * @param string $component
2226      * @return string
2227      */
2228     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2229         global $CFG;
2231         $result = '';
2233         $plugin = $this->get_submission_plugin_by_type($plugintype);
2235         $text = $plugin->get_editor_text($editor, $submissionid);
2236         $format = $plugin->get_editor_format($editor, $submissionid);
2238         $finaltext = file_rewrite_pluginfile_urls($text,
2239                                                   'pluginfile.php',
2240                                                   $this->get_context()->id,
2241                                                   $component,
2242                                                   $filearea,
2243                                                   $submissionid);
2244         $params = array('overflowdiv' => true, 'context' => $this->get_context());
2245         $result .= format_text($finaltext, $format, $params);
2247         if ($CFG->enableportfolios) {
2248             require_once($CFG->libdir . '/portfoliolib.php');
2250             $button = new portfolio_add_button();
2251             $portfolioparams = array('cmid' => $this->get_course_module()->id,
2252                                      'sid' => $submissionid,
2253                                      'plugin' => $plugintype,
2254                                      'editor' => $editor,
2255                                      'area'=>$filearea);
2256             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2257             $fs = get_file_storage();
2259             if ($files = $fs->get_area_files($this->context->id,
2260                                              $component,
2261                                              $filearea,
2262                                              $submissionid,
2263                                              'timemodified',
2264                                              false)) {
2265                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2266             } else {
2267                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2268             }
2269             $result .= $button->to_html();
2270         }
2271         return $result;
2272     }
2274     /**
2275      * Display a continue page.
2276      *
2277      * @param string $message - The message to display
2278      * @return string
2279      */
2280     protected function view_savegrading_result($message) {
2281         $o = '';
2282         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2283                                                       $this->get_context(),
2284                                                       $this->show_intro(),
2285                                                       $this->get_course_module()->id,
2286                                                       get_string('savegradingresult', 'assign')));
2287         $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2288                                                    $message,
2289                                                    $this->get_course_module()->id);
2290         $o .= $this->get_renderer()->render($gradingresult);
2291         $o .= $this->view_footer();
2292         return $o;
2293     }
2294     /**
2295      * Display a grading error.
2296      *
2297      * @param string $message - The description of the result
2298      * @return string
2299      */
2300     protected function view_quickgrading_result($message) {
2301         $o = '';
2302         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2303                                                       $this->get_context(),
2304                                                       $this->show_intro(),
2305                                                       $this->get_course_module()->id,
2306                                                       get_string('quickgradingresult', 'assign')));
2307         $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2308                                                    $message,
2309                                                    $this->get_course_module()->id);
2310         $o .= $this->get_renderer()->render($gradingresult);
2311         $o .= $this->view_footer();
2312         return $o;
2313     }
2315     /**
2316      * Display the page footer.
2317      *
2318      * @return string
2319      */
2320     protected function view_footer() {
2321         return $this->get_renderer()->render_footer();
2322     }
2324     /**
2325      * Does this user have grade permission for this assignment?
2326      *
2327      * @return bool
2328      */
2329     public function can_grade() {
2330         // Permissions check.
2331         if (!has_capability('mod/assign:grade', $this->context)) {
2332             return false;
2333         }
2335         return true;
2336     }
2338     /**
2339      * Download a zip file of all assignment submissions.
2340      *
2341      * @return string - If an error occurs, this will contain the error page.
2342      */
2343     protected function download_submissions() {
2344         global $CFG, $DB;
2346         // More efficient to load this here.
2347         require_once($CFG->libdir.'/filelib.php');
2349         require_capability('mod/assign:grade', $this->context);
2351         // Load all users with submit.
2352         $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2353                         $this->show_only_active_users());
2355         // Build a list of files to zip.
2356         $filesforzipping = array();
2357         $fs = get_file_storage();
2359         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2360         // All users.
2361         $groupid = 0;
2362         $groupname = '';
2363         if ($groupmode) {
2364             $groupid = groups_get_activity_group($this->get_course_module(), true);
2365             $groupname = groups_get_group_name($groupid).'-';
2366         }
2368         // Construct the zip file name.
2369         $filename = clean_filename($this->get_course()->shortname . '-' .
2370                                    $this->get_instance()->name . '-' .
2371                                    $groupname.$this->get_course_module()->id . '.zip');
2373         // Get all the files for each student.
2374         foreach ($students as $student) {
2375             $userid = $student->id;
2377             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2378                 // Get the plugins to add their own files to the zip.
2380                 $submissiongroup = false;
2381                 $groupname = '';
2382                 if ($this->get_instance()->teamsubmission) {
2383                     $submission = $this->get_group_submission($userid, 0, false);
2384                     $submissiongroup = $this->get_submission_group($userid);
2385                     if ($submissiongroup) {
2386                         $groupname = $submissiongroup->name . '-';
2387                     } else {
2388                         $groupname = get_string('defaultteam', 'assign') . '-';
2389                     }
2390                 } else {
2391                     $submission = $this->get_user_submission($userid, false);
2392                 }
2394                 if ($this->is_blind_marking()) {
2395                     $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2396                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2397                 } else {
2398                     $prefix = str_replace('_', ' ', $groupname . fullname($student));
2399                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2400                 }
2402                 if ($submission) {
2403                     foreach ($this->submissionplugins as $plugin) {
2404                         if ($plugin->is_enabled() && $plugin->is_visible()) {
2405                             $pluginfiles = $plugin->get_files($submission, $student);
2406                             foreach ($pluginfiles as $zipfilename => $file) {
2407                                 $subtype = $plugin->get_subtype();
2408                                 $type = $plugin->get_type();
2409                                 $prefixedfilename = clean_filename($prefix .
2410                                                                    $subtype .
2411                                                                    '_' .
2412                                                                    $type .
2413                                                                    '_' .
2414                                                                    $zipfilename);
2415                                 $filesforzipping[$prefixedfilename] = $file;
2416                             }
2417                         }
2418                     }
2419                 }
2420             }
2421         }
2422         $result = '';
2423         if (count($filesforzipping) == 0) {
2424             $header = new assign_header($this->get_instance(),
2425                                         $this->get_context(),
2426                                         '',
2427                                         $this->get_course_module()->id,
2428                                         get_string('downloadall', 'assign'));
2429             $result .= $this->get_renderer()->render($header);
2430             $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2431             $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2432                                                                     'action'=>'grading'));
2433             $result .= $this->get_renderer()->continue_button($url);
2434             $result .= $this->view_footer();
2435         } else if ($zipfile = $this->pack_files($filesforzipping)) {
2436             $addtolog = $this->add_to_log('download all submissions', get_string('downloadall', 'assign'), '', true);
2437             $params = array(
2438                 'context' => $this->context,
2439                 'objectid' => $this->get_instance()->id
2440             );
2441             $event = \mod_assign\event\all_submissions_downloaded::create($params);
2442             $event->set_legacy_logdata($addtolog);
2443             $event->trigger();
2444             // Send file and delete after sending.
2445             send_temp_file($zipfile, $filename);
2446             // We will not get here - send_temp_file calls exit.
2447         }
2448         return $result;
2449     }
2451     /**
2452      * Util function to add a message to the log.
2453      *
2454      * @param string $action The current action
2455      * @param string $info A detailed description of the change. But no more than 255 characters.
2456      * @param string $url The url to the assign module instance.
2457      * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2458      *                     retrieve the arguments to use them with the new event system (Event 2).
2459      * @return void|array
2460      */
2461     public function add_to_log($action = '', $info = '', $url='', $return = false) {
2462         global $USER;
2464         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2465         if ($url != '') {
2466             $fullurl .= '&' . $url;
2467         }
2469         $args = array(
2470             $this->get_course()->id,
2471             'assign',
2472             $action,
2473             $fullurl,
2474             $info,
2475             $this->get_course_module()->id,
2476             $USER->id
2477         );
2479         if ($return) {
2480             return $args;
2481         }
2482         call_user_func_array('add_to_log', $args);
2483     }
2485     /**
2486      * Lazy load the page renderer and expose the renderer to plugins.
2487      *
2488      * @return assign_renderer
2489      */
2490     public function get_renderer() {
2491         global $PAGE;
2492         if ($this->output) {
2493             return $this->output;
2494         }
2495         $this->output = $PAGE->get_renderer('mod_assign');
2496         return $this->output;
2497     }
2499     /**
2500      * Load the submission object for a particular user, optionally creating it if required.
2501      *
2502      * For team assignments there are 2 submissions - the student submission and the team submission
2503      * All files are associated with the team submission but the status of the students contribution is
2504      * recorded separately.
2505      *
2506      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2507      * @param bool $create optional - defaults to false. If set to true a new submission object
2508      *                     will be created in the database.
2509      * @param int $attemptnumber - -1 means the latest attempt
2510      * @return stdClass The submission
2511      */
2512     public function get_user_submission($userid, $create, $attemptnumber=-1) {
2513         global $DB, $USER;
2515         if (!$userid) {
2516             $userid = $USER->id;
2517         }
2518         // If the userid is not null then use userid.
2519         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2520         if ($attemptnumber >= 0) {
2521             $params['attemptnumber'] = $attemptnumber;
2522         }
2524         // Only return the row with the highest attemptnumber.
2525         $submission = null;
2526         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2527         if ($submissions) {
2528             $submission = reset($submissions);
2529         }
2531         if ($submission) {
2532             return $submission;
2533         }
2534         if ($create) {
2535             $submission = new stdClass();
2536             $submission->assignment   = $this->get_instance()->id;
2537             $submission->userid       = $userid;
2538             $submission->timecreated = time();
2539             $submission->timemodified = $submission->timecreated;
2540             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2541             if ($attemptnumber >= 0) {
2542                 $submission->attemptnumber = $attemptnumber;
2543             } else {
2544                 $submission->attemptnumber = 0;
2545             }
2546             $sid = $DB->insert_record('assign_submission', $submission);
2547             $submission->id = $sid;
2548             return $submission;
2549         }
2550         return false;
2551     }
2553     /**
2554      * Load the submission object from it's id.
2555      *
2556      * @param int $submissionid The id of the submission we want
2557      * @return stdClass The submission
2558      */
2559     protected function get_submission($submissionid) {
2560         global $DB;
2562         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2563         return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2564     }
2566     /**
2567      * This will retrieve a user flags object from the db optionally creating it if required.
2568      * The user flags was split from the user_grades table in 2.5.
2569      *
2570      * @param int $userid The user we are getting the flags for.
2571      * @param bool $create If true the flags record will be created if it does not exist
2572      * @return stdClass The flags record
2573      */
2574     public function get_user_flags($userid, $create) {
2575         global $DB, $USER;
2577         // If the userid is not null then use userid.
2578         if (!$userid) {
2579             $userid = $USER->id;
2580         }
2582         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2584         $flags = $DB->get_record('assign_user_flags', $params);
2586         if ($flags) {
2587             return $flags;
2588         }
2589         if ($create) {
2590             $flags = new stdClass();
2591             $flags->assignment = $this->get_instance()->id;
2592             $flags->userid = $userid;
2593             $flags->locked = 0;
2594             $flags->extensionduedate = 0;
2595             $flags->workflowstate = '';
2596             $flags->allocatedmarker = 0;
2598             // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2599             // This is because students only want to be notified about certain types of update (grades and feedback).
2600             $flags->mailed = 2;
2602             $fid = $DB->insert_record('assign_user_flags', $flags);
2603             $flags->id = $fid;
2604             return $flags;
2605         }
2606         return false;
2607     }
2609     /**
2610      * This will retrieve a grade object from the db, optionally creating it if required.
2611      *
2612      * @param int $userid The user we are grading
2613      * @param bool $create If true the grade will be created if it does not exist
2614      * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2615      * @return stdClass The grade record
2616      */
2617     public function get_user_grade($userid, $create, $attemptnumber=-1) {
2618         global $DB, $USER;
2620         // If the userid is not null then use userid.
2621         if (!$userid) {
2622             $userid = $USER->id;
2623         }
2625         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2626         if ($attemptnumber < 0) {
2627             // Make sure this grade matches the latest submission attempt.
2628             if ($this->get_instance()->teamsubmission) {
2629                 $submission = $this->get_group_submission($userid, 0, false);
2630             } else {
2631                 $submission = $this->get_user_submission($userid, false);
2632             }
2633             if ($submission) {
2634                 $attemptnumber = $submission->attemptnumber;
2635             }
2636         }
2638         if ($attemptnumber >= 0) {
2639             $params['attemptnumber'] = $attemptnumber;
2640         }
2642         $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2644         if ($grades) {
2645             return reset($grades);
2646         }
2647         if ($create) {
2648             $grade = new stdClass();
2649             $grade->assignment   = $this->get_instance()->id;
2650             $grade->userid       = $userid;
2651             $grade->timecreated = time();
2652             $grade->timemodified = $grade->timecreated;
2653             $grade->grade = -1;
2654             $grade->grader = $USER->id;
2655             if ($attemptnumber >= 0) {
2656                 $grade->attemptnumber = $attemptnumber;
2657             }
2659             $gid = $DB->insert_record('assign_grades', $grade);
2660             $grade->id = $gid;
2661             return $grade;
2662         }
2663         return false;
2664     }
2666     /**
2667      * This will retrieve a grade object from the db.
2668      *
2669      * @param int $gradeid The id of the grade
2670      * @return stdClass The grade record
2671      */
2672     protected function get_grade($gradeid) {
2673         global $DB;
2675         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2676         return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2677     }
2679     /**
2680      * Print the grading page for a single user submission.
2681      *
2682      * @param moodleform $mform
2683      * @return string
2684      */
2685     protected function view_single_grade_page($mform) {
2686         global $DB, $CFG;
2688         $o = '';
2689         $instance = $this->get_instance();
2691         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2693         // Need submit permission to submit an assignment.
2694         require_capability('mod/assign:grade', $this->context);
2696         $header = new assign_header($instance,
2697                                     $this->get_context(),
2698                                     false,
2699                                     $this->get_course_module()->id,
2700                                     get_string('grading', 'assign'));
2701         $o .= $this->get_renderer()->render($header);
2703         // If userid is passed - we are only grading a single student.
2704         $rownum = required_param('rownum', PARAM_INT);
2705         $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2706         $userid = optional_param('userid', 0, PARAM_INT);
2707         $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2709         $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2710         if (!$userid) {
2711             if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2712                 $useridlist = $this->get_grading_userid_list();
2713             }
2714             $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2715         } else {
2716             $rownum = 0;
2717             $useridlist = array($userid);
2718         }
2720         if ($rownum < 0 || $rownum > count($useridlist)) {
2721             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2722         }
2724         $last = false;
2725         $userid = $useridlist[$rownum];
2726         if ($rownum == count($useridlist) - 1) {
2727             $last = true;
2728         }
2729         $user = $DB->get_record('user', array('id' => $userid));
2730         if ($user) {
2731             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2732             $usersummary = new assign_user_summary($user,
2733                                                    $this->get_course()->id,
2734                                                    $viewfullnames,
2735                                                    $this->is_blind_marking(),
2736                                                    $this->get_uniqueid_for_user($user->id),
2737                                                    get_extra_user_fields($this->get_context()),
2738                                                    !$this->is_active_user($userid));
2739             $o .= $this->get_renderer()->render($usersummary);
2740         }
2741         $submission = $this->get_user_submission($userid, false, $attemptnumber);
2742         $submissiongroup = null;
2743         $teamsubmission = null;
2744         $notsubmitted = array();
2745         if ($instance->teamsubmission) {
2746             $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2747             $submissiongroup = $this->get_submission_group($userid);
2748             $groupid = 0;
2749             if ($submissiongroup) {
2750                 $groupid = $submissiongroup->id;
2751             }
2752             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2754         }
2756         // Get the requested grade.
2757         $grade = $this->get_user_grade($userid, false, $attemptnumber);
2758         $flags = $this->get_user_flags($userid, false);
2759         if ($this->can_view_submission($userid)) {
2760             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2761             $extensionduedate = null;
2762             if ($flags) {
2763                 $extensionduedate = $flags->extensionduedate;
2764             }
2765             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2766             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2768             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2769                                                              $instance->alwaysshowdescription,
2770                                                              $submission,
2771                                                              $instance->teamsubmission,
2772                                                              $teamsubmission,
2773                                                              $submissiongroup,
2774                                                              $notsubmitted,
2775                                                              $this->is_any_submission_plugin_enabled(),
2776                                                              $gradelocked,
2777                                                              $this->is_graded($userid),
2778                                                              $instance->duedate,
2779                                                              $instance->cutoffdate,
2780                                                              $this->get_submission_plugins(),
2781                                                              $this->get_return_action(),
2782                                                              $this->get_return_params(),
2783                                                              $this->get_course_module()->id,
2784                                                              $this->get_course()->id,
2785                                                              assign_submission_status::GRADER_VIEW,
2786                                                              $showedit,
2787                                                              false,
2788                                                              $viewfullnames,
2789                                                              $extensionduedate,
2790                                                              $this->get_context(),
2791                                                              $this->is_blind_marking(),
2792                                                              '',
2793                                                              $instance->attemptreopenmethod,
2794                                                              $instance->maxattempts);
2795             $o .= $this->get_renderer()->render($submissionstatus);
2796         }
2798         if ($grade) {
2799             $data = new stdClass();
2800             if ($grade->grade !== null && $grade->grade >= 0) {
2801                 $data->grade = format_float($grade->grade, 2);
2802             }
2803             if (!empty($flags->workflowstate)) {
2804                 $data->workflowstate = $flags->workflowstate;
2805             }
2806             if (!empty($flags->allocatedmarker)) {
2807                 $data->allocatedmarker = $flags->allocatedmarker;
2808             }
2809         } else {
2810             $data = new stdClass();
2811             $data->grade = '';
2812         }
2813         // Warning if required.
2814         $allsubmissions = $this->get_all_submissions($userid);
2816         if ($attemptnumber != -1) {
2817             $params = array('attemptnumber'=>$attemptnumber + 1,
2818                             'totalattempts'=>count($allsubmissions));
2819             $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2820             $o .= $this->get_renderer()->notification($message);
2821         }
2823         // Now show the grading form.
2824         if (!$mform) {
2825             $pagination = array('rownum'=>$rownum,
2826                                 'useridlistid'=>$useridlistid,
2827                                 'last'=>$last,
2828                                 'userid'=>optional_param('userid', 0, PARAM_INT),
2829                                 'attemptnumber'=>$attemptnumber);
2830             $formparams = array($this, $data, $pagination);
2831             $mform = new mod_assign_grade_form(null,
2832                                                $formparams,
2833                                                'post',
2834                                                '',
2835                                                array('class'=>'gradeform'));
2836         }
2837         $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2838         $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2840         if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2841             $allgrades = $this->get_all_grades($userid);
2842             $history = new assign_attempt_history($allsubmissions,
2843                                                   $allgrades,
2844                                                   $this->get_submission_plugins(),
2845                                                   $this->get_feedback_plugins(),
2846                                                   $this->get_course_module()->id,
2847                                                   $this->get_return_action(),
2848                                                   $this->get_return_params(),
2849                                                   true);
2851             $o .= $this->get_renderer()->render($history);
2852         }
2854         $msg = get_string('viewgradingformforstudent',
2855                           'assign',
2856                           array('id'=>$user->id, 'fullname'=>fullname($user)));
2857         $this->add_to_log('view grading form', $msg);
2859         $o .= $this->view_footer();
2860         return $o;
2861     }
2863     /**
2864      * Show a confirmation page to make sure they want to release student identities.
2865      *
2866      * @return string
2867      */
2868     protected function view_reveal_identities_confirm() {
2869         global $CFG, $USER;
2871         require_capability('mod/assign:revealidentities', $this->get_context());
2873         $o = '';
2874         $header = new assign_header($this->get_instance(),
2875                                     $this->get_context(),
2876                                     false,
2877                                     $this->get_course_module()->id);
2878         $o .= $this->get_renderer()->render($header);
2880         $urlparams = array('id'=>$this->get_course_module()->id,
2881                            'action'=>'revealidentitiesconfirm',
2882                            'sesskey'=>sesskey());
2883         $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2885         $urlparams = array('id'=>$this->get_course_module()->id,
2886                            'action'=>'grading');
2887         $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2889         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2890                                              $confirmurl,
2891                                              $cancelurl);
2892         $o .= $this->view_footer();
2893         $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2894         return $o;
2895     }
2897     /**
2898      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2899      *
2900      * @return string
2901      */
2902     protected function view_return_links() {
2903         $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2904         $returnparams = optional_param('returnparams', '', PARAM_TEXT);
2906         $params = array();
2907         $returnparams = str_replace('&amp;', '&', $returnparams);
2908         parse_str($returnparams, $params);
2909         $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2910         $params = array_merge($newparams, $params);
2912         $url = new moodle_url('/mod/assign/view.php', $params);
2913         return $this->get_renderer()->single_button($url, get_string('back'), 'get');
2914     }
2916     /**
2917      * View the grading table of all submissions for this assignment.
2918      *
2919      * @return string
2920      */
2921     protected function view_grading_table() {
2922         global $USER, $CFG;
2924         // Include grading options form.
2925         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2926         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2927         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2928         $o = '';
2929         $cmid = $this->get_course_module()->id;
2931         $links = array();
2932         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2933                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2934             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2935             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2936         }
2937         if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
2938             $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
2939             $links[$downloadurl] = get_string('downloadall', 'assign');
2940         }
2941         if ($this->is_blind_marking() &&
2942                 has_capability('mod/assign:revealidentities', $this->get_context())) {
2943             $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
2944             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2945         }
2946         foreach ($this->get_feedback_plugins() as $plugin) {
2947             if ($plugin->is_enabled() && $plugin->is_visible()) {
2948                 foreach ($plugin->get_grading_actions() as $action => $description) {
2949                     $url = '/mod/assign/view.php' .
2950                            '?id=' .  $cmid .
2951                            '&plugin=' . $plugin->get_type() .
2952                            '&pluginsubtype=assignfeedback' .
2953                            '&action=viewpluginpage&pluginaction=' . $action;
2954                     $links[$url] = $description;
2955                 }
2956             }
2957         }
2959         // Sort links alphabetically based on the link description.
2960         core_collator::asort($links);
2962         $gradingactions = new url_select($links);
2963         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2965         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2967         $perpage = get_user_preferences('assign_perpage', 10);
2968         $filter = get_user_preferences('assign_filter', '');
2969         $markerfilter = get_user_preferences('assign_markerfilter', '');
2970         $workflowfilter = get_user_preferences('assign_workflowfilter', '');
2971         $controller = $gradingmanager->get_active_controller();
2972         $showquickgrading = empty($controller);
2973         $quickgrading = get_user_preferences('assign_quickgrading', false);
2974         $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
2976         $markingallocation = $this->get_instance()->markingallocation &&
2977             has_capability('mod/assign:manageallocations', $this->context);
2978         // Get markers to use in drop lists.
2979         $markingallocationoptions = array();
2980         if ($markingallocation) {
2981             $markers = get_users_by_capability($this->context, 'mod/assign:grade');
2982             $markingallocationoptions[''] = get_string('filternone', 'assign');
2983             foreach ($markers as $marker) {
2984                 $markingallocationoptions[$marker->id] = fullname($marker);
2985             }
2986         }
2988         $markingworkflow = $this->get_instance()->markingworkflow;
2989         // Get marking states to show in form.
2990         $markingworkflowoptions = array();
2991         if ($markingworkflow) {
2992             $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
2993             $markingworkflowoptions[''] = get_string('filternone', 'assign');
2994             $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
2995             $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
2996         }
2998         // Print options for changing the filter and changing the number of results per page.
2999         $gradingoptionsformparams = array('cm'=>$cmid,
3000                                           'contextid'=>$this->context->id,
3001                                           'userid'=>$USER->id,
3002                                           'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
3003                                           'showquickgrading'=>$showquickgrading,
3004                                           'quickgrading'=>$quickgrading,
3005                                           'markingworkflowopt'=>$markingworkflowoptions,
3006                                           'markingallocationopt'=>$markingallocationoptions,
3007                                           'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
3008                                           'showonlyactiveenrol'=>$this->show_only_active_users());
3010         $classoptions = array('class'=>'gradingoptionsform');
3011         $gradingoptionsform = new mod_assign_grading_options_form(null,
3012                                                                   $gradingoptionsformparams,
3013                                                                   'post',
3014                                                                   '',
3015                                                                   $classoptions);
3017         $batchformparams = array('cm'=>$cmid,
3018                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3019                                  'duedate'=>$this->get_instance()->duedate,
3020                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3021                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3022                                  'context'=>$this->get_context(),
3023                                  'markingworkflow'=>$markingworkflow,
3024                                  'markingallocation'=>$markingallocation);
3025         $classoptions = array('class'=>'gradingbatchoperationsform');
3027         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
3028                                                                                    $batchformparams,
3029                                                                                    'post',
3030                                                                                    '',
3031                                                                                    $classoptions);
3033         $gradingoptionsdata = new stdClass();
3034         $gradingoptionsdata->perpage = $perpage;
3035         $gradingoptionsdata->filter = $filter;
3036         $gradingoptionsdata->markerfilter = $markerfilter;
3037         $gradingoptionsdata->workflowfilter = $workflowfilter;
3038         $gradingoptionsform->set_data($gradingoptionsdata);
3040         $actionformtext = $this->get_renderer()->render($gradingactions);
3041         $header = new assign_header($this->get_instance(),
3042                                     $this->get_context(),
3043                                     false,
3044                                     $this->get_course_module()->id,
3045                                     get_string('grading', 'assign'),
3046                                     $actionformtext);
3047         $o .= $this->get_renderer()->render($header);
3049         $currenturl = $CFG->wwwroot .
3050                       '/mod/assign/view.php?id=' .
3051                       $this->get_course_module()->id .
3052                       '&action=grading';
3054         $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3056         // Plagiarism update status apearring in the grading book.
3057         if (!empty($CFG->enableplagiarism)) {
3058             require_once($CFG->libdir . '/plagiarismlib.php');
3059             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
3060         }
3062         // Load and print the table of submissions.
3063         if ($showquickgrading && $quickgrading) {
3064             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3065             $table = $this->get_renderer()->render($gradingtable);
3066             $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
3067             $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3069             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3070         } else {
3071             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3072             $o .= $this->get_renderer()->render($gradingtable);
3073         }
3075         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3076         $users = array_keys($this->list_participants($currentgroup, true));
3077         if (count($users) != 0) {
3078             // If no enrolled user in a course then don't display the batch operations feature.
3079             $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3080             $o .= $this->get_renderer()->render($assignform);
3081         }
3082         $assignform = new assign_form('gradingoptionsform',
3083                                       $gradingoptionsform,
3084                                       'M.mod_assign.init_grading_options');
3085         $o .= $this->get_renderer()->render($assignform);
3086         return $o;
3087     }
3089     /**
3090      * View entire grading page.
3091      *
3092      * @return string
3093      */
3094     protected function view_grading_page() {
3095         global $CFG;
3097         $o = '';
3098         // Need submit permission to submit an assignment.
3099         require_capability('mod/assign:grade', $this->context);
3100         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3102         // Only load this if it is.
3104         $o .= $this->view_grading_table();
3106         $o .= $this->view_footer();
3108         $logmessage = get_string('viewsubmissiongradingtable', 'assign');
3109         $this->add_to_log('view submission grading table', $logmessage);
3110         return $o;
3111     }
3113     /**
3114      * Capture the output of the plagiarism plugins disclosures and return it as a string.
3115      *
3116      * @return void
3117      */
3118     protected function plagiarism_print_disclosure() {
3119         global $CFG;
3120         $o = '';
3122         if (!empty($CFG->enableplagiarism)) {
3123             require_once($CFG->libdir . '/plagiarismlib.php');
3125             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3126         }
3128         return $o;
3129     }
3131     /**
3132      * Message for students when assignment submissions have been closed.
3133      *
3134      * @return string
3135      */
3136     protected function view_student_error_message() {
3137         global $CFG;
3139         $o = '';
3140         // Need submit permission to submit an assignment.
3141         require_capability('mod/assign:submit', $this->context);
3143         $header = new assign_header($this->get_instance(),
3144                                     $this->get_context(),
3145                                     $this->show_intro(),
3146                                     $this->get_course_module()->id,
3147                                     get_string('editsubmission', 'assign'));
3148         $o .= $this->get_renderer()->render($header);
3150         $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
3152         $o .= $this->view_footer();
3154         return $o;
3156     }
3158     /**
3159      * View edit submissions page.
3160      *
3161      * @param moodleform $mform
3162      * @param array $notices A list of notices to display at the top of the
3163      *                       edit submission form (e.g. from plugins).
3164      * @return string The page output.
3165      */
3166     protected function view_edit_submission_page($mform, $notices) {
3167         global $CFG;
3169         $o = '';
3170         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
3171         // Need submit permission to submit an assignment.
3172         require_capability('mod/assign:submit', $this->context);
3174         if (!$this->submissions_open()) {
3175             return $this->view_student_error_message();
3176         }
3177         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3178                                                       $this->get_context(),
3179                                                       $this->show_intro(),
3180                                                       $this->get_course_module()->id,
3181                                                       get_string('editsubmission', 'assign')));
3182         $o .= $this->plagiarism_print_disclosure();
3183         $data = new stdClass();
3185         if (!$mform) {
3186             $mform = new mod_assign_submission_form(null, array($this, $data));
3187         }
3189         foreach ($notices as $notice) {
3190             $o .= $this->get_renderer()->notification($notice);
3191         }
3193         $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
3195         $o .= $this->view_footer();
3196         $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
3198         return $o;
3199     }
3201     /**
3202      * See if this assignment has a grade yet.
3203      *
3204      * @param int $userid
3205      * @return bool
3206      */
3207     protected function is_graded($userid) {
3208         $grade = $this->get_user_grade($userid, false);
3209         if ($grade) {
3210             return ($grade->grade !== null && $grade->grade >= 0);
3211         }
3212         return false;
3213     }
3215     /**
3216      * Perform an access check to see if the current $USER can view this group submission.
3217      *
3218      * @param int $groupid
3219      * @return bool
3220      */
3221     public function can_view_group_submission($groupid) {
3222         global $USER;
3224         if (has_capability('mod/assign:grade', $this->context)) {
3225             return true;
3226         }
3227         if (!is_enrolled($this->get_course_context(), $USER->id)) {
3228             return false;
3229         }
3230         $members = $this->get_submission_group_members($groupid, true);
3231         foreach ($members as $member) {
3232             if ($member->id == $USER->id) {
3233                 return true;
3234             }
3235         }
3236         return false;
3237     }
3239     /**
3240      * Perform an access check to see if the current $USER can view this users submission.
3241      *
3242      * @param int $userid
3243      * @return bool
3244      */
3245     public function can_view_submission($userid) {
3246         global $USER;
3248         if (!$this->is_active_user($userid) && !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
3249             return false;
3250         }
3251         if (has_capability('mod/assign:grade', $this->context)) {
3252             return true;
3253         }
3254         if (!is_enrolled($this->get_course_context(), $userid)) {
3255             return false;
3256         }
3257         if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
3258             return true;
3259         }
3260         return false;
3261     }
3263     /**
3264      * Allows the plugin to show a batch grading operation page.
3265      *
3266      * @param moodleform $mform
3267      * @return none
3268      */
3269     protected function view_plugin_grading_batch_operation($mform) {
3270         require_capability('mod/assign:grade', $this->context);
3271         $prefix = 'plugingradingbatchoperation_';
3273         if ($data = $mform->get_data()) {
3274             $tail = substr($data->operation, strlen($prefix));
3275             list($plugintype, $action) = explode('_', $tail, 2);
3277             $plugin = $this->get_feedback_plugin_by_type($plugintype);
3278             if ($plugin) {
3279                 $users = $data->selectedusers;
3280                 $userlist = explode(',', $users);
3281                 echo $plugin->grading_batch_operation($action, $userlist);
3282                 return;
3283             }
3284         }
3285         print_error('invalidformdata', '');
3286     }
3288     /**
3289      * Ask the user to confirm they want to perform this batch operation
3290      *
3291      * @param moodleform $mform Set to a grading batch operations form
3292      * @return string - the page to view after processing these actions
3293      */
3294     protected function process_grading_batch_operation(& $mform) {
3295         global $CFG;
3296         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3297         require_sesskey();
3299         $markingallocation = $this->get_instance()->markingallocation &&
3300             has_capability('mod/assign:manageallocations', $this->context);
3302         $batchformparams = array('cm'=>$this->get_course_module()->id,
3303                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3304                                  'duedate'=>$this->get_instance()->duedate,
3305                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3306                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3307                                  'context'=>$this->get_context(),
3308                                  'markingworkflow'=>$this->get_instance()->markingworkflow,
3309                                  'markingallocation'=>$markingallocation);
3310         $formclasses = array('class'=>'gradingbatchoperationsform');
3311         $mform = new mod_assign_grading_batch_operations_form(null,
3312                                                               $batchformparams,
3313                                                               'post',
3314                                                               '',
3315                                                               $formclasses);
3317         if ($data = $mform->get_data()) {
3318             // Get the list of users.
3319             $users = $data->selectedusers;
3320             $userlist = explode(',', $users);
3322             $prefix = 'plugingradingbatchoperation_';
3324             if ($data->operation == 'grantextension') {
3325                 // Reset the form so the grant extension page will create the extension form.
3326                 $mform = null;
3327                 return 'grantextension';
3328             } else if ($data->operation == 'setmarkingworkflowstate') {
3329                 return 'viewbatchsetmarkingworkflowstate';
3330             } else if ($data->operation == 'setmarkingallocation') {
3331                 return 'viewbatchmarkingallocation';
3332             } else if (strpos($data->operation, $prefix) === 0) {
3333                 $tail = substr($data->operation, strlen($prefix));
3334                 list($plugintype, $action) = explode('_', $tail, 2);
3336                 $plugin = $this->get_feedback_plugin_by_type($plugintype);
3337                 if ($plugin) {
3338                     return 'plugingradingbatchoperation';
3339                 }
3340             }
3342             foreach ($userlist as $userid) {
3343                 if ($data->operation == 'lock') {
3344                     $this->process_lock_submission($userid);
3345                 } else if ($data->operation == 'unlock') {
3346                     $this->process_unlock_submission($userid);
3347                 } else if ($data->operation == 'reverttodraft') {
3348                     $this->process_revert_to_draft($userid);
3349                 } else if ($data->operation == 'addattempt') {
3350                     if (!$this->get_instance()->teamsubmission) {
3351                         $this->process_add_attempt($userid);
3352                     }
3353                 }
3354             }
3355             if ($this->get_instance()->teamsubmission && $data->operation == 'addattempt') {
3356                 // This needs to be handled separately so that each team submission is only re-opened one time.
3357                 $this->process_add_attempt_group($userlist);
3358             }
3359         }
3361         return 'grading';
3362     }
3364     /**
3365      * Shows a form that allows the workflow state for selected submissions to be changed.
3366      *
3367      * @param moodleform $mform Set to a grading batch operations form
3368      * @return string - the page to view after processing these actions
3369      */
3370     private function view_batch_set_workflow_state($mform) {
3371         global $CFG, $DB;
3373         require_once($CFG->dirroot . '/mod/assign/batchsetmarkingworkflowstateform.php');
3375         $o = '';
3377         $submitteddata = $mform->get_data();
3378         $users = $submitteddata->selectedusers;
3379         $userlist = explode(',', $users);
3381         $formparams = array('cm'=>$this->get_course_module()->id,
3382                             'users'=>$userlist,
3383                             'context'=>$this->get_context());
3385         $usershtml = '';
3387         $usercount = 0;
3388         $extrauserfields = get_extra_user_fields($this->get_context());
3389         foreach ($userlist as $userid) {
3390             if ($usercount >= 5) {
3391                 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
3392                 break;
3393             }
3394             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
3396             $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
3397                                                                 $this->get_course()->id,
3398                                                                 has_capability('moodle/site:viewfullnames',
3399                                                                 $this->get_course_context()),
3400                                                                 $this->is_blind_marking(),
3401                                                                 $this->get_uniqueid_for_user($user->id),
3402                                                                 $extrauserfields,
3403                                                                 !$this->is_active_user($userid)));
3404             $usercount += 1;
3405         }
3407         $formparams['usershtml'] = $usershtml;
3408         $formparams['markingworkflowstates'] = $this->get_marking_workflow_states_for_current_user();
3410         $mform = new mod_assign_batch_set_marking_workflow_state_form(null, $formparams);
3411         $o .= $this->get_renderer()->header();
3412         $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
3413         $o .= $this->view_footer();
3415         $this->add_to_log('view batch set marking workflow state', get_string('viewbatchsetmarkingworkflowstate', 'assign'));
3416         return $o;
3417     }
3419     /**
3420      * Shows a form that allows the allocated marker for selected submissions to be changed.
3421      *
3422      * @param moodleform $mform Set to a grading batch operations form
3423      * @return string - the page to view after processing these actions
3424      */
3425     private function view_batch_markingallocation($mform) {
3426         global $CFG, $DB;
3428         require_once($CFG->dirroot . '/mod/assign/batchsetallocatedmarkerform.php');
3430         $o = '';
3432         $submitteddata = $mform->get_data();
3433         $users = $submitteddata->selectedusers;
3434         $userlist = explode(',', $users);
3436         $formparams = array('cm'=>$this->get_course_module()->id,
3437             'users'=>$userlist,
3438             'context'=>$this->get_context());
3440         $usershtml = '';
3442         $usercount = 0;
3443         $extrauserfields = get_extra_user_fields($this->get_context());
3444         foreach ($userlist as $userid) {
3445             if ($usercount >= 5) {
3446                 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
3447                 break;
3448             }
3449             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
3451             $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
3452                 $this->get_course()->id,
3453                 has_capability('moodle/site:viewfullnames',
3454                 $this->get_course_context()),
3455                 $this->is_blind_marking(),
3456                 $this->get_uniqueid_for_user($user->id),
3457                 $extrauserfields,
3458                 !$this->is_active_user($userid)));
3459             $usercount += 1;
3460         }
3462         $formparams['usershtml'] = $usershtml;
3463         $markers = get_users_by_capability($this->get_context(), 'mod/assign:grade');
3464         $markerlist = array();
3465         foreach ($markers as $marker) {
3466             $markerlist[$marker->id] = fullname($marker);
3467         }
3469         $formparams['markers'] = $markerlist;
3471         $mform = new mod_assign_batch_set_allocatedmarker_form(null, $formparams);
3472         $o .= $this->get_renderer()->header();
3473         $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
3474         $o .= $this->view_footer();
3476         $this->add_to_log('view batch set marker allocation', get_string('viewbatchmarkingallocation', 'assign'));
3477         return $o;
3478     }
3480     /**
3481      * Ask the user to confirm they want to submit their work for grading.
3482      *
3483      * @param moodleform $mform - null unless form validation has failed
3484      * @return string
3485      */
3486     protected function check_submit_for_grading($mform) {
3487         global $USER, $CFG;
3489         require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
3491         // Check that all of the submission plugins are ready for this submission.
3492         $notifications = array();
3493         $submission = $this->get_user_submission($USER->id, false);
3494         $plugins = $this->get_submission_plugins();
3495         foreach ($plugins as $plugin) {
3496             if ($plugin->is_enabled() && $plugin->is_visible()) {
3497                 $check = $plugin->precheck_submission($submission);
3498                 if ($check !== true) {
3499                     $notifications[] = $check;
3500                 }
3501             }
3502         }
3504         $data = new stdClass();
3505         $adminconfig = $this->get_admin_config();
3506         $requiresubmissionstatement = $this->get_instance()->requiresubmissionstatement &&
3507                                        !empty($adminconfig->submissionstatement);
3509         $submissionstatement = '';
3510         if (!empty($adminconfig->submissionstatement)) {
3511             $submissionstatement = $adminconfig->submissionstatement;
3512         }
3514         if ($mform == null) {
3515             $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
3516                                                                         $submissionstatement,
3517                                                                         $this->get_course_module()->id,
3518                                                                         $data));
3519         }
3520         $o = '';
3521         $o .= $this->get_renderer()->header();
3522         $submitforgradingpage = new assign_submit_for_grading_page($notifications,
3523                                                                    $this->get_course_module()->id,
3524                                                                    $mform);
3525         $o .= $this->get_renderer()->render($submitforgradingpage);
3526         $o .= $this->view_footer();
3528         $logmessage = get_string('viewownsubmissionform', 'assign');
3529         $this->add_to_log('view confirm submit assignment form', $logmessage);
3531         return $o;
3532     }
3534     /**
3535      * Print 2 tables of information with no action links -
3536      * the submission summary and the grading summary.
3537      *
3538      * @param stdClass $user the user to print the report for
3539      * @param bool $showlinks - Return plain text or links to the profile
3540      * @return string - the html summary
3541      */
3542     public function view_student_summary($user, $showlinks) {
3543         global $CFG, $DB, $PAGE;
3545         $instance = $this->get_instance();
3546         $grade = $this->get_user_grade($user->id, false);
3547         $flags = $this->get_user_flags($user->id, false);
3548         $submission = $this->get_user_submission($user->id, false);
3549         $o = '';
3551         $teamsubmission = null;
3552         $submissiongroup = null;
3553         $notsubmitted = array();
3554         if ($instance->teamsubmission) {
3555             $teamsubmission = $this->get_group_submission($user->id, 0, false);
3556             $submissiongroup = $this->get_submission_group($user->id);
3557             $groupid = 0;
3558             if ($submissiongroup) {
3559                 $groupid = $submissiongroup->id;
3560             }
3561             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
3562         }
3564         if ($this->can_view_submission($user->id)) {
3565             $showedit = has_capability('mod/assign:submit', $this->context) &&
3566                         $this->submissions_open($user->id) &&
3567                         ($this->is_any_submission_plugin_enabled()) &&
3568                         $showlinks;
3570             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($user->id, false);
3572             // Grading criteria preview.
3573             $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
3574             $gradingcontrollerpreview = '';
3575             if ($gradingmethod = $gradingmanager->get_active_method()) {
3576                 $controller = $gradingmanager->get_controller($gradingmethod);
3577                 if ($controller->is_form_defined()) {
3578                     $gradingcontrollerpreview = $controller->render_preview($PAGE);
3579                 }
3580             }
3582             $showsubmit = ($showlinks && $this->submissions_open($user->id));
3583             $showsubmit = ($showsubmit && $this->show_submit_button($submission, $teamsubmission));
3585             $extensionduedate = null;
3586             if ($flags) {
3587                 $extensionduedate = $flags->extensionduedate;
3588             }
3589             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
3591             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
3592                                                               $instance->alwaysshowdescription,
3593                                                               $submission,
3594                                                               $instance->teamsubmission,
3595                                                               $teamsubmission,
3596                                                               $submissiongroup,
3597                                                               $notsubmitted,
3598                                                               $this->is_any_submission_plugin_enabled(),
3599                                                               $gradelocked,
3600                                                               $this->is_graded($user->id),
3601                                                               $instance->duedate,
3602                                                               $instance->cutoffdate,
3603                                                               $this->get_submission_plugins(),
3604                                                               $this->get_return_action(),
3605                                                               $this->get_return_params(),
3606                                                               $this->get_course_module()->id,
3607                                                               $this->get_course()->id,
3608                                                               assign_submission_status::STUDENT_VIEW,
3609                                                               $showedit,
3610                                                               $showsubmit,
3611                                                               $viewfullnames,
3612                                                               $extensionduedate,
3613                                                               $this->get_context(),
3614                                                               $this->is_blind_marking(),
3615                                                               $gradingcontrollerpreview,
3616                                                               $instance->attemptreopenmethod,
3617                                                               $instance->maxattempts);
3618             $o .= $this->get_renderer()->render($submissionstatus);
3620             require_once($CFG->libdir.'/gradelib.php');
3621             require_once($CFG->dirroot.'/grade/grading/lib.php');
3623             $gradinginfo = grade_get_grades($this->get_course()->id,
3624                                         'mod',
3625                                         'assign',
3626                                         $instance->id,
3627                                         $user->id);
3629             $gradingitem = null;
3630             $gradebookgrade = null;
3631             if (isset($gradinginfo->items[0])) {
3632                 $gradingitem = $gradinginfo->items[0];
3633                 $gradebookgrade = $gradingitem->grades[$user->id];
3634             }
3636             // Check to see if all feedback plugins are empty.
3637             $emptyplugins = true;
3638             if ($grade) {
3639                 foreach ($this->get_feedback_plugins() as $plugin) {
3640                     if ($plugin->is_visible() && $plugin->is_enabled()) {
3641                         if (!$plugin->is_empty($grade)) {
3642                             $emptyplugins = false;
3643                         }
3644                     }
3645                 }
3646             }
3648             $gradereleased = true;
3649             if ($this->get_instance()->markingworkflow &&
3650                 (empty($grade) || $flags->workflowstate != ASSIGN_MARKING_WORKFLOW_STATE_RELEASED)) {
3651                 $gradereleased = false;
3652                 $emptyplugins = true; // Don't show feedback plugins until released either.
3653             }
3655             $cangrade = has_capability('mod/assign:grade', $this->get_context());
3656             // If there is a visible grade, show the summary.
3657             if ((!empty($gradebookgrade->grade) || !$emptyplugins)
3658                     && ($cangrade || !$gradebookgrade->hidden)) {
3660                 $gradefordisplay = null;
3661                 $gradeddate = null;
3662                 $grader = null;
3663                 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3665                 // Only show the grade if it is not hidden in gradebook.
3666                 if (!empty($gradebookgrade->grade) && ($cangrade || !$gradebookgrade->hidden)) {
3667                     if ($controller = $gradingmanager->get_active_controller()) {
3668                         $menu = make_grades_menu($this->get_instance()->grade);
3669                         $controller->set_grade_range($menu, $this->get_instance()->grade > 0);
3670                         $gradefordisplay = $controller->render_grade($PAGE,
3671                                                                      $grade->id,
3672                                                                      $gradingitem,
3673                                                                      $gradebookgrade->str_long_grade,
3674                                                                      $cangrade);
3675                     } else {
3676                         $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
3677                     }
3678                     $gradeddate = $gradebookgrade->dategraded;
3679                     if (isset($grade->grader)) {
3680                         $grader = $DB->get_record('user', array('id'=>$grade->grader));
3681                     }
3682                 }
3684                 $feedbackstatus = new assign_feedback_status($gradefordisplay,
3685                                                       $gradeddate,
3686                                                       $grader,
3687                                                       $this->get_feedback_plugins(),
3688                                                       $grade,
3689                                                       $this->get_course_module()->id,
3690                                                       $this->get_return_action(),
3691                                                       $this->get_return_params());
3693                 $o .= $this->get_renderer()->render($feedbackstatus);
3694             }
3696             $allsubmissions = $this->get_all_submissions($user->id);
3698             if (count($allsubmissions) > 1) {
3699                 $allgrades = $this->get_all_grades($user->id);
3700                 $history = new assign_attempt_history($allsubmissions,
3701                                                       $allgrades,
3702                                                       $this->get_submission_plugins(),
3703                                                       $this->get_feedback_plugins(),
3704                                                       $this->get_course_module()->id,
3705                                                       $this->get_return_action(),
3706                                                       $this->get_return_params(),
3707                                                       false);
3709                 $o .= $this->get_renderer()->render($history);
3710             }
3712         }
3713         return $o;
3714     }
3716     /**
3717      * Returns true if the submit subsission button should be shown to the user.
3718      *
3719      * @param stdClass $submission The users own submission record.
3720      * @param stdClass $teamsubmission The users team submission record if there is one
3721      * @return bool
3722      */
3723     protected function show_submit_button($submission = null, $teamsubmission = null) {
3724         if ($teamsubmission) {
3725             if ($teamsubmission->status === ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
3726                 // The assignment submission has been completed.
3727                 return false;
3728             } else if ($this->submission_empty($teamsubmission)) {
3729