MDL-42919 Assign: Remove no-label form hacks
[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                 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
948             }
949         }
950     }
954     /**
955      * Add one plugins settings to edit plugin form.
956      *
957      * @param assign_plugin $plugin The plugin to add the settings from
958      * @param MoodleQuickForm $mform The form to add the configuration settings to.
959      *                               This form is modified directly (not returned).
960      * @param array $pluginsenabled A list of form elements to be added to a group.
961      *                              The new element is added to this array by this function.
962      * @return void
963      */
964     protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
965         global $CFG;
966         if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
967             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
968             $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
969             $mform->setType($name, PARAM_BOOL);
970             $plugin->get_settings($mform);
971         } else if ($plugin->is_visible() && $plugin->is_configurable()) {
972             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
973             $label = $plugin->get_name();
974             $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
975             $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
977             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
978             if ($plugin->get_config('enabled') !== false) {
979                 $default = $plugin->is_enabled();
980             }
981             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
983             $plugin->get_settings($mform);
985         }
986     }
988     /**
989      * Add settings to edit plugin form.
990      *
991      * @param MoodleQuickForm $mform The form to add the configuration settings to.
992      *                               This form is modified directly (not returned).
993      * @return void
994      */
995     public function add_all_plugin_settings(MoodleQuickForm $mform) {
996         $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
998         $submissionpluginsenabled = array();
999         $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1000         foreach ($this->submissionplugins as $plugin) {
1001             $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1002         }
1003         $group->setElements($submissionpluginsenabled);
1005         $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1006         $feedbackpluginsenabled = array();
1007         $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1008         foreach ($this->feedbackplugins as $plugin) {
1009             $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1010         }
1011         $group->setElements($feedbackpluginsenabled);
1012         $mform->setExpanded('submissiontypes');
1013     }
1015     /**
1016      * Allow each plugin an opportunity to update the defaultvalues
1017      * passed in to the settings form (needed to set up draft areas for
1018      * editor and filemanager elements)
1019      *
1020      * @param array $defaultvalues
1021      */
1022     public function plugin_data_preprocessing(&$defaultvalues) {
1023         foreach ($this->submissionplugins as $plugin) {
1024             if ($plugin->is_visible()) {
1025                 $plugin->data_preprocessing($defaultvalues);
1026             }
1027         }
1028         foreach ($this->feedbackplugins as $plugin) {
1029             if ($plugin->is_visible()) {
1030                 $plugin->data_preprocessing($defaultvalues);
1031             }
1032         }
1033     }
1035     /**
1036      * Get the name of the current module.
1037      *
1038      * @return string the module name (Assignment)
1039      */
1040     protected function get_module_name() {
1041         if (isset(self::$modulename)) {
1042             return self::$modulename;
1043         }
1044         self::$modulename = get_string('modulename', 'assign');
1045         return self::$modulename;
1046     }
1048     /**
1049      * Get the plural name of the current module.
1050      *
1051      * @return string the module name plural (Assignments)
1052      */
1053     protected function get_module_name_plural() {
1054         if (isset(self::$modulenameplural)) {
1055             return self::$modulenameplural;
1056         }
1057         self::$modulenameplural = get_string('modulenameplural', 'assign');
1058         return self::$modulenameplural;
1059     }
1061     /**
1062      * Has this assignment been constructed from an instance?
1063      *
1064      * @return bool
1065      */
1066     public function has_instance() {
1067         return $this->instance || $this->get_course_module();
1068     }
1070     /**
1071      * Get the settings for the current instance of this assignment
1072      *
1073      * @return stdClass The settings
1074      */
1075     public function get_instance() {
1076         global $DB;
1077         if ($this->instance) {
1078             return $this->instance;
1079         }
1080         if ($this->get_course_module()) {
1081             $params = array('id' => $this->get_course_module()->instance);
1082             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1083         }
1084         if (!$this->instance) {
1085             throw new coding_exception('Improper use of the assignment class. ' .
1086                                        'Cannot load the assignment record.');
1087         }
1088         return $this->instance;
1089     }
1091     /**
1092      * Get the primary grade item for this assign instance.
1093      *
1094      * @return stdClass The grade_item record
1095      */
1096     public function get_grade_item() {
1097         if ($this->gradeitem) {
1098             return $this->gradeitem;
1099         }
1100         $instance = $this->get_instance();
1101         $params = array('itemtype' => 'mod',
1102                         'itemmodule' => 'assign',
1103                         'iteminstance' => $instance->id,
1104                         'courseid' => $instance->course,
1105                         'itemnumber' => 0);
1106         $this->gradeitem = grade_item::fetch($params);
1107         if (!$this->gradeitem) {
1108             throw new coding_exception('Improper use of the assignment class. ' .
1109                                        'Cannot load the grade item.');
1110         }
1111         return $this->gradeitem;
1112     }
1114     /**
1115      * Get the context of the current course.
1116      *
1117      * @return mixed context|null The course context
1118      */
1119     public function get_course_context() {
1120         if (!$this->context && !$this->course) {
1121             throw new coding_exception('Improper use of the assignment class. ' .
1122                                        'Cannot load the course context.');
1123         }
1124         if ($this->context) {
1125             return $this->context->get_course_context();
1126         } else {
1127             return context_course::instance($this->course->id);
1128         }
1129     }
1132     /**
1133      * Get the current course module.
1134      *
1135      * @return mixed stdClass|null The course module
1136      */
1137     public function get_course_module() {
1138         if ($this->coursemodule) {
1139             return $this->coursemodule;
1140         }
1141         if (!$this->context) {
1142             return null;
1143         }
1145         if ($this->context->contextlevel == CONTEXT_MODULE) {
1146             $this->coursemodule = get_coursemodule_from_id('assign',
1147                                                            $this->context->instanceid,
1148                                                            0,
1149                                                            false,
1150                                                            MUST_EXIST);
1151             return $this->coursemodule;
1152         }
1153         return null;
1154     }
1156     /**
1157      * Get context module.
1158      *
1159      * @return context
1160      */
1161     public function get_context() {
1162         return $this->context;
1163     }
1165     /**
1166      * Get the current course.
1167      *
1168      * @return mixed stdClass|null The course
1169      */
1170     public function get_course() {
1171         global $DB;
1173         if ($this->course) {
1174             return $this->course;
1175         }
1177         if (!$this->context) {
1178             return null;
1179         }
1180         $params = array('id' => $this->get_course_context()->instanceid);
1181         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1183         return $this->course;
1184     }
1186     /**
1187      * Return a grade in user-friendly form, whether it's a scale or not.
1188      *
1189      * @param mixed $grade int|null
1190      * @param boolean $editing Are we allowing changes to this grade?
1191      * @param int $userid The user id the grade belongs to
1192      * @param int $modified Timestamp from when the grade was last modified
1193      * @return string User-friendly representation of grade
1194      */
1195     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1196         global $DB;
1198         static $scalegrades = array();
1200         $o = '';
1202         if ($this->get_instance()->grade >= 0) {
1203             // Normal number.
1204             if ($editing && $this->get_instance()->grade > 0) {
1205                 if ($grade < 0) {
1206                     $displaygrade = '';
1207                 } else {
1208                     $displaygrade = format_float($grade, 2);
1209                 }
1210                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1211                        get_string('usergrade', 'assign') .
1212                        '</label>';
1213                 $o .= '<input type="text"
1214                               id="quickgrade_' . $userid . '"
1215                               name="quickgrade_' . $userid . '"
1216                               value="' .  $displaygrade . '"
1217                               size="6"
1218                               maxlength="10"
1219                               class="quickgrade"/>';
1220                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1221                 $o .= '<input type="hidden"
1222                               name="grademodified_' . $userid . '"
1223                               value="' . $modified . '"/>';
1224                 return $o;
1225             } else {
1226                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1227                 if ($grade == -1 || $grade === null) {
1228                     $o .= '-';
1229                 } else {
1230                     $item = $this->get_grade_item();
1231                     $o .= grade_format_gradevalue($grade, $item);
1232                     if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1233                         // If displaying the raw grade, also display the total value.
1234                         $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1235                     }
1236                 }
1237                 return $o;
1238             }
1240         } else {
1241             // Scale.
1242             if (empty($this->cache['scale'])) {
1243                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1244                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1245                 } else {
1246                     $o .= '-';
1247                     return $o;
1248                 }
1249             }
1250             if ($editing) {
1251                 $o .= '<label class="accesshide"
1252                               for="quickgrade_' . $userid . '">' .
1253                       get_string('usergrade', 'assign') .
1254                       '</label>';
1255                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1256                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1257                 foreach ($this->cache['scale'] as $optionid => $option) {
1258                     $selected = '';
1259                     if ($grade == $optionid) {
1260                         $selected = 'selected="selected"';
1261                     }
1262                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1263                 }
1264                 $o .= '</select>';
1265                 $o .= '<input type="hidden" ' .
1266                              'name="grademodified_' . $userid . '" ' .
1267                              'value="' . $modified . '"/>';
1268                 return $o;
1269             } else {
1270                 $scaleid = (int)$grade;
1271                 if (isset($this->cache['scale'][$scaleid])) {
1272                     $o .= $this->cache['scale'][$scaleid];
1273                     return $o;
1274                 }
1275                 $o .= '-';
1276                 return $o;
1277             }
1278         }
1279     }
1281     /**
1282      * Load a list of users enrolled in the current course with the specified permission and group.
1283      * 0 for no group.
1284      *
1285      * @param int $currentgroup
1286      * @param bool $idsonly
1287      * @return array List of user records
1288      */
1289     public function list_participants($currentgroup, $idsonly) {
1290         if ($idsonly) {
1291             $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.id', null, null, null,
1292                     $this->show_only_active_users());
1293         } else {
1294             $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', null, null, null,
1295                     $this->show_only_active_users());
1296         }
1298         $cm = $this->get_course_module();
1299         foreach ($users as $userid => $user) {
1300             if (!groups_course_module_visible($cm, $userid)) {
1301                 unset($users[$userid]);
1302             }
1303         }
1305         return $users;
1306     }
1308     /**
1309      * Load a count of valid teams for this assignment.
1310      *
1311      * @return int number of valid teams
1312      */
1313     public function count_teams() {
1315         $groups = groups_get_all_groups($this->get_course()->id,
1316                                         0,
1317                                         $this->get_instance()->teamsubmissiongroupingid,
1318                                         'g.id');
1319         $count = count($groups);
1321         // See if there are any users in the default group.
1322         $defaultusers = $this->get_submission_group_members(0, true);
1323         if (count($defaultusers) > 0) {
1324             $count += 1;
1325         }
1326         return $count;
1327     }
1329     /**
1330      * Load a count of active users enrolled in the current course with the specified permission and group.
1331      * 0 for no group.
1332      *
1333      * @param int $currentgroup
1334      * @return int number of matching users
1335      */
1336     public function count_participants($currentgroup) {
1337         return count($this->list_participants($currentgroup, true));
1338     }
1340     /**
1341      * Load a count of active users submissions in the current module that require grading
1342      * This means the submission modification time is more recent than the
1343      * grading modification time and the status is SUBMITTED.
1344      *
1345      * @return int number of matching submissions
1346      */
1347     public function count_submissions_need_grading() {
1348         global $DB;
1350         if ($this->get_instance()->teamsubmission) {
1351             // This does not make sense for group assignment because the submission is shared.
1352             return 0;
1353         }
1355         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1356         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1358         $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1359                                  FROM {assign_submission} mxs
1360                                  WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1361         $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1362                             FROM {assign_grades} mxg
1363                             WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1365         $params['assignid'] = $this->get_instance()->id;
1366         $params['assignid2'] = $this->get_instance()->id;
1367         $params['assignid3'] = $this->get_instance()->id;
1368         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1370         $sql = 'SELECT COUNT(s.userid)
1371                    FROM {assign_submission} s
1372                    LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1373                    LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1374                    LEFT JOIN {assign_grades} g ON
1375                         s.assignment = g.assignment AND
1376                         s.userid = g.userid AND
1377                         g.attemptnumber = gmx.maxattempt
1378                    JOIN(' . $esql . ') e ON e.id = s.userid
1379                    WHERE
1380                         s.attemptnumber = smx.maxattempt AND
1381                         s.assignment = :assignid AND
1382                         s.timemodified IS NOT NULL AND
1383                         s.status = :submitted AND
1384                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1386         return $DB->count_records_sql($sql, $params);
1387     }
1389     /**
1390      * Load a count of grades.
1391      *
1392      * @return int number of grades
1393      */
1394     public function count_grades() {
1395         global $DB;
1397         if (!$this->has_instance()) {
1398             return 0;
1399         }
1401         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1402         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1404         $params['assignid'] = $this->get_instance()->id;
1406         $sql = 'SELECT COUNT(g.userid)
1407                    FROM {assign_grades} g
1408                    JOIN(' . $esql . ') e ON e.id = g.userid
1409                    WHERE g.assignment = :assignid';
1411         return $DB->count_records_sql($sql, $params);
1412     }
1414     /**
1415      * Load a count of submissions.
1416      *
1417      * @return int number of submissions
1418      */
1419     public function count_submissions() {
1420         global $DB;
1422         if (!$this->has_instance()) {
1423             return 0;
1424         }
1426         $params = array();
1428         if ($this->get_instance()->teamsubmission) {
1429             // We cannot join on the enrolment tables for group submissions (no userid).
1430             $sql = 'SELECT COUNT(DISTINCT s.groupid)
1431                         FROM {assign_submission} s
1432                         WHERE
1433                             s.assignment = :assignid AND
1434                             s.timemodified IS NOT NULL AND
1435                             s.userid = :groupuserid';
1437             $params['assignid'] = $this->get_instance()->id;
1438             $params['groupuserid'] = 0;
1439         } else {
1440             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1441             list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1443             $params['assignid'] = $this->get_instance()->id;
1445             $sql = 'SELECT COUNT(DISTINCT s.userid)
1446                        FROM {assign_submission} s
1447                        JOIN(' . $esql . ') e ON e.id = s.userid
1448                        WHERE
1449                             s.assignment = :assignid AND
1450                             s.timemodified IS NOT NULL';
1452         }
1454         return $DB->count_records_sql($sql, $params);
1455     }
1457     /**
1458      * Load a count of submissions with a specified status.
1459      *
1460      * @param string $status The submission status - should match one of the constants
1461      * @return int number of matching submissions
1462      */
1463     public function count_submissions_with_status($status) {
1464         global $DB;
1466         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1467         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1469         $params['assignid'] = $this->get_instance()->id;
1470         $params['assignid2'] = $this->get_instance()->id;
1471         $params['submissionstatus'] = $status;
1473         if ($this->get_instance()->teamsubmission) {
1474             $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1475                               FROM {assign_submission} mxs
1476                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1478             $sql = 'SELECT COUNT(s.groupid)
1479                         FROM {assign_submission} s
1480                         JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1481                         WHERE
1482                             s.attemptnumber = smx.maxattempt AND
1483                             s.assignment = :assignid AND
1484                             s.timemodified IS NOT NULL AND
1485                             s.userid = :groupuserid AND
1486                             s.status = :submissionstatus';
1487             $params['groupuserid'] = 0;
1488         } else {
1489             $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1490                               FROM {assign_submission} mxs
1491                               WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1493             $sql = 'SELECT COUNT(s.userid)
1494                         FROM {assign_submission} s
1495                         JOIN(' . $esql . ') e ON e.id = s.userid
1496                         JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1497                         WHERE
1498                             s.attemptnumber = smx.maxattempt AND
1499                             s.assignment = :assignid AND
1500                             s.timemodified IS NOT NULL AND
1501                             s.status = :submissionstatus';
1503         }
1505         return $DB->count_records_sql($sql, $params);
1506     }
1508     /**
1509      * Utility function to get the userid for every row in the grading table
1510      * so the order can be frozen while we iterate it.
1511      *
1512      * @return array An array of userids
1513      */
1514     protected function get_grading_userid_list() {
1515         $filter = get_user_preferences('assign_filter', '');
1516         $table = new assign_grading_table($this, 0, $filter, 0, false);
1518         $useridlist = $table->get_column_data('userid');
1520         return $useridlist;
1521     }
1523     /**
1524      * Generate zip file from array of given files.
1525      *
1526      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1527      *                                 This array is indexed by the final file name and each
1528      *                                 element in the array is an instance of a stored_file object.
1529      * @return path of temp file - note this returned file does
1530      *         not have a .zip extension - it is a temp file.
1531      */
1532     protected function pack_files($filesforzipping) {
1533         global $CFG;
1534         // Create path for new zip file.
1535         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1536         // Zip files.
1537         $zipper = new zip_packer();
1538         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1539             return $tempzip;
1540         }
1541         return false;
1542     }
1544     /**
1545      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1546      *
1547      * Cron function to be run periodically according to the moodle cron.
1548      *
1549      * @return bool
1550      */
1551     public static function cron() {
1552         global $DB;
1554         // Only ever send a max of one days worth of updates.
1555         $yesterday = time() - (24 * 3600);
1556         $timenow   = time();
1558         // Collect all submissions from the past 24 hours that require mailing.
1559         $sql = 'SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
1560                        g.*, g.timemodified as lastmodified
1561                  FROM {assign} a
1562                  JOIN {assign_grades} g ON g.assignment = a.id
1563                  LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1564                 WHERE g.timemodified >= :yesterday AND
1565                       g.timemodified <= :today AND
1566                       uf.mailed = 0';
1568         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1569         $submissions = $DB->get_records_sql($sql, $params);
1571         if (empty($submissions)) {
1572             return true;
1573         }
1575         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1577         // Preload courses we are going to need those.
1578         $courseids = array();
1579         foreach ($submissions as $submission) {
1580             $courseids[] = $submission->course;
1581         }
1583         // Filter out duplicates.
1584         $courseids = array_unique($courseids);
1585         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1586         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1587         $sql = 'SELECT c.*, ' . $ctxselect .
1588                   ' FROM {course} c
1589              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1590                  WHERE c.id ' . $courseidsql;
1592         $params['contextlevel'] = CONTEXT_COURSE;
1593         $courses = $DB->get_records_sql($sql, $params);
1595         // Clean up... this could go on for a while.
1596         unset($courseids);
1597         unset($ctxselect);
1598         unset($courseidsql);
1599         unset($params);
1601         // Simple array we'll use for caching modules.
1602         $modcache = array();
1604         // Message students about new feedback.
1605         foreach ($submissions as $submission) {
1607             mtrace("Processing assignment submission $submission->id ...");
1609             // Do not cache user lookups - could be too many.
1610             if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1611                 mtrace('Could not find user ' . $submission->userid);
1612                 continue;
1613             }
1615             // Use a cache to prevent the same DB queries happening over and over.
1616             if (!array_key_exists($submission->course, $courses)) {
1617                 mtrace('Could not find course ' . $submission->course);
1618                 continue;
1619             }
1620             $course = $courses[$submission->course];
1621             if (isset($course->ctxid)) {
1622                 // Context has not yet been preloaded. Do so now.
1623                 context_helper::preload_from_record($course);
1624             }
1626             // Override the language and timezone of the "current" user, so that
1627             // mail is customised for the receiver.
1628             cron_setup_user($user, $course);
1630             // Context lookups are already cached.
1631             $coursecontext = context_course::instance($course->id);
1632             if (!is_enrolled($coursecontext, $user->id)) {
1633                 $courseshortname = format_string($course->shortname,
1634                                                  true,
1635                                                  array('context' => $coursecontext));
1636                 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1637                 continue;
1638             }
1640             if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1641                 mtrace('Could not find grader ' . $submission->grader);
1642                 continue;
1643             }
1645             if (!array_key_exists($submission->assignment, $modcache)) {
1646                 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1647                 if (empty($mod)) {
1648                     mtrace('Could not find course module for assignment id ' . $submission->assignment);
1649                     continue;
1650                 }
1651                 $modcache[$submission->assignment] = $mod;
1652             } else {
1653                 $mod = $modcache[$submission->assignment];
1654             }
1655             // Context lookups are already cached.
1656             $contextmodule = context_module::instance($mod->id);
1658             if (!$mod->visible) {
1659                 // Hold mail notification for hidden assignments until later.
1660                 continue;
1661             }
1663             // Need to send this to the student.
1664             $messagetype = 'feedbackavailable';
1665             $eventtype = 'assign_notification';
1666             $updatetime = $submission->lastmodified;
1667             $modulename = get_string('modulename', 'assign');
1669             $uniqueid = 0;
1670             if ($submission->blindmarking && !$submission->revealidentities) {
1671                 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1672             }
1673             $showusers = $submission->blindmarking && !$submission->revealidentities;
1674             self::send_assignment_notification($grader,
1675                                                $user,
1676                                                $messagetype,
1677                                                $eventtype,
1678                                                $updatetime,
1679                                                $mod,
1680                                                $contextmodule,
1681                                                $course,
1682                                                $modulename,
1683                                                $submission->name,
1684                                                $showusers,
1685                                                $uniqueid);
1687             $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1688             if ($flags) {
1689                 $flags->mailed = 1;
1690                 $DB->update_record('assign_user_flags', $flags);
1691             } else {
1692                 $flags = new stdClass();
1693                 $flags->userid = $user->id;
1694                 $flags->assignment = $submission->assignment;
1695                 $flags->mailed = 1;
1696                 $DB->insert_record('assign_user_flags', $flags);
1697             }
1699             mtrace('Done');
1700         }
1701         mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1703         cron_setup_user();
1705         // Free up memory just to be sure.
1706         unset($courses);
1707         unset($modcache);
1709         return true;
1710     }
1712     /**
1713      * Mark in the database that this grade record should have an update notification sent by cron.
1714      *
1715      * @param stdClass $grade a grade record keyed on id
1716      * @return bool true for success
1717      */
1718     public function notify_grade_modified($grade) {
1719         global $DB;
1721         $flags = $this->get_user_flags($grade->userid, true);
1722         if ($flags->mailed != 1) {
1723             $flags->mailed = 0;
1724         }
1726         return $this->update_user_flags($flags);
1727     }
1729     /**
1730      * Update user flags for this user in this assignment.
1731      *
1732      * @param stdClass $flags a flags record keyed on id
1733      * @return bool true for success
1734      */
1735     public function update_user_flags($flags) {
1736         global $DB;
1737         if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1738             return false;
1739         }
1741         $result = $DB->update_record('assign_user_flags', $flags);
1742         return $result;
1743     }
1745     /**
1746      * Update a grade in the grade table for the assignment and in the gradebook.
1747      *
1748      * @param stdClass $grade a grade record keyed on id
1749      * @return bool true for success
1750      */
1751     public function update_grade($grade) {
1752         global $DB;
1754         $grade->timemodified = time();
1756         if (!empty($grade->workflowstate)) {
1757             $validstates = $this->get_marking_workflow_states_for_current_user();
1758             if (!array_key_exists($grade->workflowstate, $validstates)) {
1759                 return false;
1760             }
1761         }
1763         if ($grade->grade && $grade->grade != -1) {
1764             if ($this->get_instance()->grade > 0) {
1765                 if (!is_numeric($grade->grade)) {
1766                     return false;
1767                 } else if ($grade->grade > $this->get_instance()->grade) {
1768                     return false;
1769                 } else if ($grade->grade < 0) {
1770                     return false;
1771                 }
1772             } else {
1773                 // This is a scale.
1774                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1775                     $scaleoptions = make_menu_from_list($scale->scale);
1776                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1777                         return false;
1778                     }
1779                 }
1780             }
1781         }
1783         if (empty($grade->attemptnumber)) {
1784             // Set it to the default.
1785             $grade->attemptnumber = 0;
1786         }
1787         $result = $DB->update_record('assign_grades', $grade);
1789         // Only push to gradebook if the update is for the latest attempt.
1790         $submission = null;
1791         if ($this->get_instance()->teamsubmission) {
1792             $submission = $this->get_group_submission($grade->userid, 0, false);
1793         } else {
1794             $submission = $this->get_user_submission($grade->userid, false);
1795         }
1796         // Not the latest attempt.
1797         if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1798             return true;
1799         }
1801         if ($result) {
1802             $this->gradebook_item_update(null, $grade);
1803         }
1804         return $result;
1805     }
1807     /**
1808      * View the grant extension date page.
1809      *
1810      * Uses url parameters 'userid'
1811      * or from parameter 'selectedusers'
1812      *
1813      * @param moodleform $mform - Used for validation of the submitted data
1814      * @return string
1815      */
1816     protected function view_grant_extension($mform) {
1817         global $DB, $CFG;
1818         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1820         $o = '';
1821         $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1822         $data = new stdClass();
1823         $data->extensionduedate = null;
1824         $userid = 0;
1825         if (!$batchusers) {
1826             $userid = required_param('userid', PARAM_INT);
1828             $grade = $this->get_user_grade($userid, false);
1830             $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1832             if ($grade) {
1833                 $data->extensionduedate = $grade->extensionduedate;
1834             }
1835             $data->userid = $userid;
1836         } else {
1837             $data->batchusers = $batchusers;
1838         }
1839         $header = new assign_header($this->get_instance(),
1840                                     $this->get_context(),
1841                                     $this->show_intro(),
1842                                     $this->get_course_module()->id,
1843                                     get_string('grantextension', 'assign'));
1844         $o .= $this->get_renderer()->render($header);
1846         if (!$mform) {
1847             $formparams = array($this->get_course_module()->id,
1848                                 $userid,
1849                                 $batchusers,
1850                                 $this->get_instance(),
1851                                 $data);
1852             $mform = new mod_assign_extension_form(null, $formparams);
1853         }
1854         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1855         $o .= $this->view_footer();
1856         return $o;
1857     }
1859     /**
1860      * Get a list of the users in the same group as this user.
1861      *
1862      * @param int $groupid The id of the group whose members we want or 0 for the default group
1863      * @param bool $onlyids Whether to retrieve only the user id's
1864      * @return array The users (possibly id's only)
1865      */
1866     public function get_submission_group_members($groupid, $onlyids) {
1867         $members = array();
1868         if ($groupid != 0) {
1869             if ($onlyids) {
1870                 $allusers = groups_get_members($groupid, 'u.id');
1871             } else {
1872                 $allusers = groups_get_members($groupid);
1873             }
1874             foreach ($allusers as $user) {
1875                 if ($this->get_submission_group($user->id)) {
1876                     $members[] = $user;
1877                 }
1878             }
1879         } else {
1880             $allusers = $this->list_participants(null, $onlyids);
1881             foreach ($allusers as $user) {
1882                 if ($this->get_submission_group($user->id) == null) {
1883                     $members[] = $user;
1884                 }
1885             }
1886         }
1887         // Exclude suspended users, if user can't see them.
1888         if (!has_capability('moodle/course:viewsuspendedusers', $this->context)) {
1889             foreach ($members as $key => $member) {
1890                 if (!$this->is_active_user($member->id)) {
1891                     unset($members[$key]);
1892                 }
1893             }
1894         }
1895         return $members;
1896     }
1898     /**
1899      * Get a list of the users in the same group as this user that have not submitted the assignment.
1900      *
1901      * @param int $groupid The id of the group whose members we want or 0 for the default group
1902      * @param bool $onlyids Whether to retrieve only the user id's
1903      * @return array The users (possibly id's only)
1904      */
1905     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1906         $instance = $this->get_instance();
1907         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1908             return array();
1909         }
1910         $members = $this->get_submission_group_members($groupid, $onlyids);
1912         foreach ($members as $id => $member) {
1913             $submission = $this->get_user_submission($member->id, false);
1914             if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1915                 unset($members[$id]);
1916             } else {
1917                 if ($this->is_blind_marking()) {
1918                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
1919                                            $this->get_uniqueid_for_user($id);
1920                 }
1921             }
1922         }
1923         return $members;
1924     }
1926     /**
1927      * Load the group submission object for a particular user, optionally creating it if required.
1928      *
1929      * @param int $userid The id of the user whose submission we want
1930      * @param int $groupid The id of the group for this user - may be 0 in which
1931      *                     case it is determined from the userid.
1932      * @param bool $create If set to true a new submission object will be created in the database
1933      * @param int $attemptnumber - -1 means the latest attempt
1934      * @return stdClass The submission
1935      */
1936     public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
1937         global $DB;
1939         if ($groupid == 0) {
1940             $group = $this->get_submission_group($userid);
1941             if ($group) {
1942                 $groupid = $group->id;
1943             }
1944         }
1946         // Now get the group submission.
1947         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1948         if ($attemptnumber >= 0) {
1949             $params['attemptnumber'] = $attemptnumber;
1950         }
1952         // Only return the row with the highest attemptnumber.
1953         $submission = null;
1954         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
1955         if ($submissions) {
1956             $submission = reset($submissions);
1957         }
1959         if ($submission) {
1960             return $submission;
1961         }
1962         if ($create) {
1963             $submission = new stdClass();
1964             $submission->assignment = $this->get_instance()->id;
1965             $submission->userid = 0;
1966             $submission->groupid = $groupid;
1967             $submission->timecreated = time();
1968             $submission->timemodified = $submission->timecreated;
1969             if ($attemptnumber >= 0) {
1970                 $submission->attemptnumber = $attemptnumber;
1971             } else {
1972                 $submission->attemptnumber = 0;
1973             }
1975             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1976             $sid = $DB->insert_record('assign_submission', $submission);
1977             $submission->id = $sid;
1978             return $submission;
1979         }
1980         return false;
1981     }
1983     /**
1984      * View a summary listing of all assignments in the current course.
1985      *
1986      * @return string
1987      */
1988     private function view_course_index() {
1989         global $USER;
1991         $o = '';
1993         $course = $this->get_course();
1994         $strplural = get_string('modulenameplural', 'assign');
1996         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
1997             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
1998             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
1999             return $o;
2000         }
2002         $strsectionname = '';
2003         $usesections = course_format_uses_sections($course->format);
2004         $modinfo = get_fast_modinfo($course);
2006         if ($usesections) {
2007             $strsectionname = get_string('sectionname', 'format_'.$course->format);
2008             $sections = $modinfo->get_section_info_all();
2009         }
2010         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2012         $timenow = time();
2014         $currentsection = '';
2015         foreach ($modinfo->instances['assign'] as $cm) {
2016             if (!$cm->uservisible) {
2017                 continue;
2018             }
2020             $timedue = $cms[$cm->id]->duedate;
2022             $sectionname = '';
2023             if ($usesections && $cm->sectionnum) {
2024                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2025             }
2027             $submitted = '';
2028             $context = context_module::instance($cm->id);
2030             $assignment = new assign($context, $cm, $course);
2032             if (has_capability('mod/assign:grade', $context)) {
2033                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2035             } else if (has_capability('mod/assign:submit', $context)) {
2036                 $usersubmission = $assignment->get_user_submission($USER->id, false);
2038                 if (!empty($usersubmission->status)) {
2039                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2040                 } else {
2041                     $submitted = get_string('submissionstatus_', 'assign');
2042                 }
2043             }
2044             $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2045             if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2046                     !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2047                 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2048             } else {
2049                 $grade = '-';
2050             }
2052             $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2054         }
2056         $o .= $this->get_renderer()->render($courseindexsummary);
2057         $o .= $this->view_footer();
2059         return $o;
2060     }
2062     /**
2063      * View a page rendered by a plugin.
2064      *
2065      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2066      *
2067      * @return string
2068      */
2069     protected function view_plugin_page() {
2070         global $USER;
2072         $o = '';
2074         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2075         $plugintype = required_param('plugin', PARAM_TEXT);
2076         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2078         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2079         if (!$plugin) {
2080             print_error('invalidformdata', '');
2081             return;
2082         }
2084         $o .= $plugin->view_page($pluginaction);
2086         return $o;
2087     }
2090     /**
2091      * This is used for team assignments to get the group for the specified user.
2092      * If the user is a member of multiple or no groups this will return false
2093      *
2094      * @param int $userid The id of the user whose submission we want
2095      * @return mixed The group or false
2096      */
2097     public function get_submission_group($userid) {
2098         $grouping = $this->get_instance()->teamsubmissiongroupingid;
2099         $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2100         if (count($groups) != 1) {
2101             return false;
2102         }
2103         return array_pop($groups);
2104     }
2107     /**
2108      * Display the submission that is used by a plugin.
2109      *
2110      * Uses url parameters 'sid', 'gid' and 'plugin'.
2111      *
2112      * @param string $pluginsubtype
2113      * @return string
2114      */
2115     protected function view_plugin_content($pluginsubtype) {
2116         global $USER;
2118         $o = '';
2120         $submissionid = optional_param('sid', 0, PARAM_INT);
2121         $gradeid = optional_param('gid', 0, PARAM_INT);
2122         $plugintype = required_param('plugin', PARAM_TEXT);
2123         $item = null;
2124         if ($pluginsubtype == 'assignsubmission') {
2125             $plugin = $this->get_submission_plugin_by_type($plugintype);
2126             if ($submissionid <= 0) {
2127                 throw new coding_exception('Submission id should not be 0');
2128             }
2129             $item = $this->get_submission($submissionid);
2131             // Check permissions.
2132             if ($item->userid != $USER->id) {
2133                 require_capability('mod/assign:grade', $this->context);
2134             }
2135             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2136                                                               $this->get_context(),
2137                                                               $this->show_intro(),
2138                                                               $this->get_course_module()->id,
2139                                                               $plugin->get_name()));
2140             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2141                                                               $item,
2142                                                               assign_submission_plugin_submission::FULL,
2143                                                               $this->get_course_module()->id,
2144                                                               $this->get_return_action(),
2145                                                               $this->get_return_params()));
2147             $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
2148             $this->add_to_log('view submission', $logmessage);
2149         } else {
2150             $plugin = $this->get_feedback_plugin_by_type($plugintype);
2151             if ($gradeid <= 0) {
2152                 throw new coding_exception('Grade id should not be 0');
2153             }
2154             $item = $this->get_grade($gradeid);
2155             // Check permissions.
2156             if ($item->userid != $USER->id) {
2157                 require_capability('mod/assign:grade', $this->context);
2158             }
2159             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2160                                                               $this->get_context(),
2161                                                               $this->show_intro(),
2162                                                               $this->get_course_module()->id,
2163                                                               $plugin->get_name()));
2164             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2165                                                               $item,
2166                                                               assign_feedback_plugin_feedback::FULL,
2167                                                               $this->get_course_module()->id,
2168                                                               $this->get_return_action(),
2169                                                               $this->get_return_params()));
2170             $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
2171             $this->add_to_log('view feedback', $logmessage);
2172         }
2174         $o .= $this->view_return_links();
2176         $o .= $this->view_footer();
2177         return $o;
2178     }
2180     /**
2181      * Rewrite plugin file urls so they resolve correctly in an exported zip.
2182      *
2183      * @param string $text - The replacement text
2184      * @param stdClass $user - The user record
2185      * @param assign_plugin $plugin - The assignment plugin
2186      */
2187     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2188         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2189         $groupname = '';
2190         if ($groupmode) {
2191             $groupid = groups_get_activity_group($this->get_course_module(), true);
2192             $groupname = groups_get_group_name($groupid).'-';
2193         }
2195         if ($this->is_blind_marking()) {
2196             $prefix = $groupname . get_string('participant', 'assign');
2197             $prefix = str_replace('_', ' ', $prefix);
2198             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2199         } else {
2200             $prefix = $groupname . fullname($user);
2201             $prefix = str_replace('_', ' ', $prefix);
2202             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2203         }
2205         $subtype = $plugin->get_subtype();
2206         $type = $plugin->get_type();
2207         $prefix = $prefix . $subtype . '_' . $type . '_';
2209         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2211         return $result;
2212     }
2214     /**
2215      * Render the content in editor that is often used by plugin.
2216      *
2217      * @param string $filearea
2218      * @param int  $submissionid
2219      * @param string $plugintype
2220      * @param string $editor
2221      * @param string $component
2222      * @return string
2223      */
2224     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2225         global $CFG;
2227         $result = '';
2229         $plugin = $this->get_submission_plugin_by_type($plugintype);
2231         $text = $plugin->get_editor_text($editor, $submissionid);
2232         $format = $plugin->get_editor_format($editor, $submissionid);
2234         $finaltext = file_rewrite_pluginfile_urls($text,
2235                                                   'pluginfile.php',
2236                                                   $this->get_context()->id,
2237                                                   $component,
2238                                                   $filearea,
2239                                                   $submissionid);
2240         $params = array('overflowdiv' => true, 'context' => $this->get_context());
2241         $result .= format_text($finaltext, $format, $params);
2243         if ($CFG->enableportfolios) {
2244             require_once($CFG->libdir . '/portfoliolib.php');
2246             $button = new portfolio_add_button();
2247             $portfolioparams = array('cmid' => $this->get_course_module()->id,
2248                                      'sid' => $submissionid,
2249                                      'plugin' => $plugintype,
2250                                      'editor' => $editor,
2251                                      'area'=>$filearea);
2252             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2253             $fs = get_file_storage();
2255             if ($files = $fs->get_area_files($this->context->id,
2256                                              $component,
2257                                              $filearea,
2258                                              $submissionid,
2259                                              'timemodified',
2260                                              false)) {
2261                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2262             } else {
2263                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2264             }
2265             $result .= $button->to_html();
2266         }
2267         return $result;
2268     }
2270     /**
2271      * Display a continue page.
2272      *
2273      * @param string $message - The message to display
2274      * @return string
2275      */
2276     protected function view_savegrading_result($message) {
2277         $o = '';
2278         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2279                                                       $this->get_context(),
2280                                                       $this->show_intro(),
2281                                                       $this->get_course_module()->id,
2282                                                       get_string('savegradingresult', 'assign')));
2283         $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2284                                                    $message,
2285                                                    $this->get_course_module()->id);
2286         $o .= $this->get_renderer()->render($gradingresult);
2287         $o .= $this->view_footer();
2288         return $o;
2289     }
2290     /**
2291      * Display a grading error.
2292      *
2293      * @param string $message - The description of the result
2294      * @return string
2295      */
2296     protected function view_quickgrading_result($message) {
2297         $o = '';
2298         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2299                                                       $this->get_context(),
2300                                                       $this->show_intro(),
2301                                                       $this->get_course_module()->id,
2302                                                       get_string('quickgradingresult', 'assign')));
2303         $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2304                                                    $message,
2305                                                    $this->get_course_module()->id);
2306         $o .= $this->get_renderer()->render($gradingresult);
2307         $o .= $this->view_footer();
2308         return $o;
2309     }
2311     /**
2312      * Display the page footer.
2313      *
2314      * @return string
2315      */
2316     protected function view_footer() {
2317         return $this->get_renderer()->render_footer();
2318     }
2320     /**
2321      * Does this user have grade permission for this assignment?
2322      *
2323      * @return bool
2324      */
2325     public function can_grade() {
2326         // Permissions check.
2327         if (!has_capability('mod/assign:grade', $this->context)) {
2328             return false;
2329         }
2331         return true;
2332     }
2334     /**
2335      * Download a zip file of all assignment submissions.
2336      *
2337      * @return string - If an error occurs, this will contain the error page.
2338      */
2339     protected function download_submissions() {
2340         global $CFG, $DB;
2342         // More efficient to load this here.
2343         require_once($CFG->libdir.'/filelib.php');
2345         require_capability('mod/assign:grade', $this->context);
2347         // Load all users with submit.
2348         $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2349                         $this->show_only_active_users());
2351         // Build a list of files to zip.
2352         $filesforzipping = array();
2353         $fs = get_file_storage();
2355         $groupmode = groups_get_activity_groupmode($this->get_course_module());
2356         // All users.
2357         $groupid = 0;
2358         $groupname = '';
2359         if ($groupmode) {
2360             $groupid = groups_get_activity_group($this->get_course_module(), true);
2361             $groupname = groups_get_group_name($groupid).'-';
2362         }
2364         // Construct the zip file name.
2365         $filename = clean_filename($this->get_course()->shortname . '-' .
2366                                    $this->get_instance()->name . '-' .
2367                                    $groupname.$this->get_course_module()->id . '.zip');
2369         // Get all the files for each student.
2370         foreach ($students as $student) {
2371             $userid = $student->id;
2373             if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2374                 // Get the plugins to add their own files to the zip.
2376                 $submissiongroup = false;
2377                 $groupname = '';
2378                 if ($this->get_instance()->teamsubmission) {
2379                     $submission = $this->get_group_submission($userid, 0, false);
2380                     $submissiongroup = $this->get_submission_group($userid);
2381                     if ($submissiongroup) {
2382                         $groupname = $submissiongroup->name . '-';
2383                     } else {
2384                         $groupname = get_string('defaultteam', 'assign') . '-';
2385                     }
2386                 } else {
2387                     $submission = $this->get_user_submission($userid, false);
2388                 }
2390                 if ($this->is_blind_marking()) {
2391                     $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2392                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2393                 } else {
2394                     $prefix = str_replace('_', ' ', $groupname . fullname($student));
2395                     $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2396                 }
2398                 if ($submission) {
2399                     foreach ($this->submissionplugins as $plugin) {
2400                         if ($plugin->is_enabled() && $plugin->is_visible()) {
2401                             $pluginfiles = $plugin->get_files($submission, $student);
2402                             foreach ($pluginfiles as $zipfilename => $file) {
2403                                 $subtype = $plugin->get_subtype();
2404                                 $type = $plugin->get_type();
2405                                 $prefixedfilename = clean_filename($prefix .
2406                                                                    $subtype .
2407                                                                    '_' .
2408                                                                    $type .
2409                                                                    '_' .
2410                                                                    $zipfilename);
2411                                 $filesforzipping[$prefixedfilename] = $file;
2412                             }
2413                         }
2414                     }
2415                 }
2416             }
2417         }
2418         $result = '';
2419         if (count($filesforzipping) == 0) {
2420             $header = new assign_header($this->get_instance(),
2421                                         $this->get_context(),
2422                                         '',
2423                                         $this->get_course_module()->id,
2424                                         get_string('downloadall', 'assign'));
2425             $result .= $this->get_renderer()->render($header);
2426             $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2427             $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2428                                                                     'action'=>'grading'));
2429             $result .= $this->get_renderer()->continue_button($url);
2430             $result .= $this->view_footer();
2431         } else if ($zipfile = $this->pack_files($filesforzipping)) {
2432             $addtolog = $this->add_to_log('download all submissions', get_string('downloadall', 'assign'), '', true);
2433             $params = array(
2434                 'context' => $this->context,
2435                 'objectid' => $this->get_instance()->id
2436             );
2437             $event = \mod_assign\event\all_submissions_downloaded::create($params);
2438             $event->set_legacy_logdata($addtolog);
2439             $event->trigger();
2440             // Send file and delete after sending.
2441             send_temp_file($zipfile, $filename);
2442             // We will not get here - send_temp_file calls exit.
2443         }
2444         return $result;
2445     }
2447     /**
2448      * Util function to add a message to the log.
2449      *
2450      * @param string $action The current action
2451      * @param string $info A detailed description of the change. But no more than 255 characters.
2452      * @param string $url The url to the assign module instance.
2453      * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2454      *                     retrieve the arguments to use them with the new event system (Event 2).
2455      * @return void|array
2456      */
2457     public function add_to_log($action = '', $info = '', $url='', $return = false) {
2458         global $USER;
2460         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2461         if ($url != '') {
2462             $fullurl .= '&' . $url;
2463         }
2465         $args = array(
2466             $this->get_course()->id,
2467             'assign',
2468             $action,
2469             $fullurl,
2470             $info,
2471             $this->get_course_module()->id,
2472             $USER->id
2473         );
2475         if ($return) {
2476             return $args;
2477         }
2478         call_user_func_array('add_to_log', $args);
2479     }
2481     /**
2482      * Lazy load the page renderer and expose the renderer to plugins.
2483      *
2484      * @return assign_renderer
2485      */
2486     public function get_renderer() {
2487         global $PAGE;
2488         if ($this->output) {
2489             return $this->output;
2490         }
2491         $this->output = $PAGE->get_renderer('mod_assign');
2492         return $this->output;
2493     }
2495     /**
2496      * Load the submission object for a particular user, optionally creating it if required.
2497      *
2498      * For team assignments there are 2 submissions - the student submission and the team submission
2499      * All files are associated with the team submission but the status of the students contribution is
2500      * recorded separately.
2501      *
2502      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2503      * @param bool $create optional - defaults to false. If set to true a new submission object
2504      *                     will be created in the database.
2505      * @param int $attemptnumber - -1 means the latest attempt
2506      * @return stdClass The submission
2507      */
2508     public function get_user_submission($userid, $create, $attemptnumber=-1) {
2509         global $DB, $USER;
2511         if (!$userid) {
2512             $userid = $USER->id;
2513         }
2514         // If the userid is not null then use userid.
2515         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2516         if ($attemptnumber >= 0) {
2517             $params['attemptnumber'] = $attemptnumber;
2518         }
2520         // Only return the row with the highest attemptnumber.
2521         $submission = null;
2522         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2523         if ($submissions) {
2524             $submission = reset($submissions);
2525         }
2527         if ($submission) {
2528             return $submission;
2529         }
2530         if ($create) {
2531             $submission = new stdClass();
2532             $submission->assignment   = $this->get_instance()->id;
2533             $submission->userid       = $userid;
2534             $submission->timecreated = time();
2535             $submission->timemodified = $submission->timecreated;
2536             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2537             if ($attemptnumber >= 0) {
2538                 $submission->attemptnumber = $attemptnumber;
2539             } else {
2540                 $submission->attemptnumber = 0;
2541             }
2542             $sid = $DB->insert_record('assign_submission', $submission);
2543             $submission->id = $sid;
2544             return $submission;
2545         }
2546         return false;
2547     }
2549     /**
2550      * Load the submission object from it's id.
2551      *
2552      * @param int $submissionid The id of the submission we want
2553      * @return stdClass The submission
2554      */
2555     protected function get_submission($submissionid) {
2556         global $DB;
2558         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2559         return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2560     }
2562     /**
2563      * This will retrieve a user flags object from the db optionally creating it if required.
2564      * The user flags was split from the user_grades table in 2.5.
2565      *
2566      * @param int $userid The user we are getting the flags for.
2567      * @param bool $create If true the flags record will be created if it does not exist
2568      * @return stdClass The flags record
2569      */
2570     public function get_user_flags($userid, $create) {
2571         global $DB, $USER;
2573         // If the userid is not null then use userid.
2574         if (!$userid) {
2575             $userid = $USER->id;
2576         }
2578         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2580         $flags = $DB->get_record('assign_user_flags', $params);
2582         if ($flags) {
2583             return $flags;
2584         }
2585         if ($create) {
2586             $flags = new stdClass();
2587             $flags->assignment = $this->get_instance()->id;
2588             $flags->userid = $userid;
2589             $flags->locked = 0;
2590             $flags->extensionduedate = 0;
2591             $flags->workflowstate = '';
2592             $flags->allocatedmarker = 0;
2594             // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2595             // This is because students only want to be notified about certain types of update (grades and feedback).
2596             $flags->mailed = 2;
2598             $fid = $DB->insert_record('assign_user_flags', $flags);
2599             $flags->id = $fid;
2600             return $flags;
2601         }
2602         return false;
2603     }
2605     /**
2606      * This will retrieve a grade object from the db, optionally creating it if required.
2607      *
2608      * @param int $userid The user we are grading
2609      * @param bool $create If true the grade will be created if it does not exist
2610      * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2611      * @return stdClass The grade record
2612      */
2613     public function get_user_grade($userid, $create, $attemptnumber=-1) {
2614         global $DB, $USER;
2616         // If the userid is not null then use userid.
2617         if (!$userid) {
2618             $userid = $USER->id;
2619         }
2621         $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2622         if ($attemptnumber < 0) {
2623             // Make sure this grade matches the latest submission attempt.
2624             if ($this->get_instance()->teamsubmission) {
2625                 $submission = $this->get_group_submission($userid, 0, false);
2626             } else {
2627                 $submission = $this->get_user_submission($userid, false);
2628             }
2629             if ($submission) {
2630                 $attemptnumber = $submission->attemptnumber;
2631             }
2632         }
2634         if ($attemptnumber >= 0) {
2635             $params['attemptnumber'] = $attemptnumber;
2636         }
2638         $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2640         if ($grades) {
2641             return reset($grades);
2642         }
2643         if ($create) {
2644             $grade = new stdClass();
2645             $grade->assignment   = $this->get_instance()->id;
2646             $grade->userid       = $userid;
2647             $grade->timecreated = time();
2648             $grade->timemodified = $grade->timecreated;
2649             $grade->grade = -1;
2650             $grade->grader = $USER->id;
2651             if ($attemptnumber >= 0) {
2652                 $grade->attemptnumber = $attemptnumber;
2653             }
2655             $gid = $DB->insert_record('assign_grades', $grade);
2656             $grade->id = $gid;
2657             return $grade;
2658         }
2659         return false;
2660     }
2662     /**
2663      * This will retrieve a grade object from the db.
2664      *
2665      * @param int $gradeid The id of the grade
2666      * @return stdClass The grade record
2667      */
2668     protected function get_grade($gradeid) {
2669         global $DB;
2671         $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2672         return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2673     }
2675     /**
2676      * Print the grading page for a single user submission.
2677      *
2678      * @param moodleform $mform
2679      * @return string
2680      */
2681     protected function view_single_grade_page($mform) {
2682         global $DB, $CFG;
2684         $o = '';
2685         $instance = $this->get_instance();
2687         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2689         // Need submit permission to submit an assignment.
2690         require_capability('mod/assign:grade', $this->context);
2692         $header = new assign_header($instance,
2693                                     $this->get_context(),
2694                                     false,
2695                                     $this->get_course_module()->id,
2696                                     get_string('grading', 'assign'));
2697         $o .= $this->get_renderer()->render($header);
2699         // If userid is passed - we are only grading a single student.
2700         $rownum = required_param('rownum', PARAM_INT);
2701         $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2702         $userid = optional_param('userid', 0, PARAM_INT);
2703         $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2705         $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2706         if (!$userid) {
2707             if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2708                 $useridlist = $this->get_grading_userid_list();
2709             }
2710             $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2711         } else {
2712             $rownum = 0;
2713             $useridlist = array($userid);
2714         }
2716         if ($rownum < 0 || $rownum > count($useridlist)) {
2717             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2718         }
2720         $last = false;
2721         $userid = $useridlist[$rownum];
2722         if ($rownum == count($useridlist) - 1) {
2723             $last = true;
2724         }
2725         $user = $DB->get_record('user', array('id' => $userid));
2726         if ($user) {
2727             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2728             $usersummary = new assign_user_summary($user,
2729                                                    $this->get_course()->id,
2730                                                    $viewfullnames,
2731                                                    $this->is_blind_marking(),
2732                                                    $this->get_uniqueid_for_user($user->id),
2733                                                    get_extra_user_fields($this->get_context()),
2734                                                    !$this->is_active_user($userid));
2735             $o .= $this->get_renderer()->render($usersummary);
2736         }
2737         $submission = $this->get_user_submission($userid, false, $attemptnumber);
2738         $submissiongroup = null;
2739         $teamsubmission = null;
2740         $notsubmitted = array();
2741         if ($instance->teamsubmission) {
2742             $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2743             $submissiongroup = $this->get_submission_group($userid);
2744             $groupid = 0;
2745             if ($submissiongroup) {
2746                 $groupid = $submissiongroup->id;
2747             }
2748             $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2750         }
2752         // Get the requested grade.
2753         $grade = $this->get_user_grade($userid, false, $attemptnumber);
2754         $flags = $this->get_user_flags($userid, false);
2755         if ($this->can_view_submission($userid)) {
2756             $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2757             $extensionduedate = null;
2758             if ($flags) {
2759                 $extensionduedate = $flags->extensionduedate;
2760             }
2761             $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2762             $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2764             $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2765                                                              $instance->alwaysshowdescription,
2766                                                              $submission,
2767                                                              $instance->teamsubmission,
2768                                                              $teamsubmission,
2769                                                              $submissiongroup,
2770                                                              $notsubmitted,
2771                                                              $this->is_any_submission_plugin_enabled(),
2772                                                              $gradelocked,
2773                                                              $this->is_graded($userid),
2774                                                              $instance->duedate,
2775                                                              $instance->cutoffdate,
2776                                                              $this->get_submission_plugins(),
2777                                                              $this->get_return_action(),
2778                                                              $this->get_return_params(),
2779                                                              $this->get_course_module()->id,
2780                                                              $this->get_course()->id,
2781                                                              assign_submission_status::GRADER_VIEW,
2782                                                              $showedit,
2783                                                              false,
2784                                                              $viewfullnames,
2785                                                              $extensionduedate,
2786                                                              $this->get_context(),
2787                                                              $this->is_blind_marking(),
2788                                                              '',
2789                                                              $instance->attemptreopenmethod,
2790                                                              $instance->maxattempts);
2791             $o .= $this->get_renderer()->render($submissionstatus);
2792         }
2794         if ($grade) {
2795             $data = new stdClass();
2796             if ($grade->grade !== null && $grade->grade >= 0) {
2797                 $data->grade = format_float($grade->grade, 2);
2798             }
2799             if (!empty($flags->workflowstate)) {
2800                 $data->workflowstate = $flags->workflowstate;
2801             }
2802             if (!empty($flags->allocatedmarker)) {
2803                 $data->allocatedmarker = $flags->allocatedmarker;
2804             }
2805         } else {
2806             $data = new stdClass();
2807             $data->grade = '';
2808         }
2809         // Warning if required.
2810         $allsubmissions = $this->get_all_submissions($userid);
2812         if ($attemptnumber != -1) {
2813             $params = array('attemptnumber'=>$attemptnumber + 1,
2814                             'totalattempts'=>count($allsubmissions));
2815             $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2816             $o .= $this->get_renderer()->notification($message);
2817         }
2819         // Now show the grading form.
2820         if (!$mform) {
2821             $pagination = array('rownum'=>$rownum,
2822                                 'useridlistid'=>$useridlistid,
2823                                 'last'=>$last,
2824                                 'userid'=>optional_param('userid', 0, PARAM_INT),
2825                                 'attemptnumber'=>$attemptnumber);
2826             $formparams = array($this, $data, $pagination);
2827             $mform = new mod_assign_grade_form(null,
2828                                                $formparams,
2829                                                'post',
2830                                                '',
2831                                                array('class'=>'gradeform'));
2832         }
2833         $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2834         $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2836         if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2837             $allgrades = $this->get_all_grades($userid);
2838             $history = new assign_attempt_history($allsubmissions,
2839                                                   $allgrades,
2840                                                   $this->get_submission_plugins(),
2841                                                   $this->get_feedback_plugins(),
2842                                                   $this->get_course_module()->id,
2843                                                   $this->get_return_action(),
2844                                                   $this->get_return_params(),
2845                                                   true);
2847             $o .= $this->get_renderer()->render($history);
2848         }
2850         $msg = get_string('viewgradingformforstudent',
2851                           'assign',
2852                           array('id'=>$user->id, 'fullname'=>fullname($user)));
2853         $this->add_to_log('view grading form', $msg);
2855         $o .= $this->view_footer();
2856         return $o;
2857     }
2859     /**
2860      * Show a confirmation page to make sure they want to release student identities.
2861      *
2862      * @return string
2863      */
2864     protected function view_reveal_identities_confirm() {
2865         global $CFG, $USER;
2867         require_capability('mod/assign:revealidentities', $this->get_context());
2869         $o = '';
2870         $header = new assign_header($this->get_instance(),
2871                                     $this->get_context(),
2872                                     false,
2873                                     $this->get_course_module()->id);
2874         $o .= $this->get_renderer()->render($header);
2876         $urlparams = array('id'=>$this->get_course_module()->id,
2877                            'action'=>'revealidentitiesconfirm',
2878                            'sesskey'=>sesskey());
2879         $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2881         $urlparams = array('id'=>$this->get_course_module()->id,
2882                            'action'=>'grading');
2883         $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2885         $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2886                                              $confirmurl,
2887                                              $cancelurl);
2888         $o .= $this->view_footer();
2889         $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2890         return $o;
2891     }
2893     /**
2894      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2895      *
2896      * @return string
2897      */
2898     protected function view_return_links() {
2899         $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2900         $returnparams = optional_param('returnparams', '', PARAM_TEXT);
2902         $params = array();
2903         $returnparams = str_replace('&amp;', '&', $returnparams);
2904         parse_str($returnparams, $params);
2905         $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2906         $params = array_merge($newparams, $params);
2908         $url = new moodle_url('/mod/assign/view.php', $params);
2909         return $this->get_renderer()->single_button($url, get_string('back'), 'get');
2910     }
2912     /**
2913      * View the grading table of all submissions for this assignment.
2914      *
2915      * @return string
2916      */
2917     protected function view_grading_table() {
2918         global $USER, $CFG;
2920         // Include grading options form.
2921         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2922         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2923         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2924         $o = '';
2925         $cmid = $this->get_course_module()->id;
2927         $links = array();
2928         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2929                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2930             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2931             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2932         }
2933         if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
2934             $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
2935             $links[$downloadurl] = get_string('downloadall', 'assign');
2936         }
2937         if ($this->is_blind_marking() &&
2938                 has_capability('mod/assign:revealidentities', $this->get_context())) {
2939             $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
2940             $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2941         }
2942         foreach ($this->get_feedback_plugins() as $plugin) {
2943             if ($plugin->is_enabled() && $plugin->is_visible()) {
2944                 foreach ($plugin->get_grading_actions() as $action => $description) {
2945                     $url = '/mod/assign/view.php' .
2946                            '?id=' .  $cmid .
2947                            '&plugin=' . $plugin->get_type() .
2948                            '&pluginsubtype=assignfeedback' .
2949                            '&action=viewpluginpage&pluginaction=' . $action;
2950                     $links[$url] = $description;
2951                 }
2952             }
2953         }
2955         // Sort links alphabetically based on the link description.
2956         core_collator::asort($links);
2958         $gradingactions = new url_select($links);
2959         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2961         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2963         $perpage = get_user_preferences('assign_perpage', 10);
2964         $filter = get_user_preferences('assign_filter', '');
2965         $markerfilter = get_user_preferences('assign_markerfilter', '');
2966         $workflowfilter = get_user_preferences('assign_workflowfilter', '');
2967         $controller = $gradingmanager->get_active_controller();
2968         $showquickgrading = empty($controller);
2969         $quickgrading = get_user_preferences('assign_quickgrading', false);
2970         $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
2972         $markingallocation = $this->get_instance()->markingallocation &&
2973             has_capability('mod/assign:manageallocations', $this->context);
2974         // Get markers to use in drop lists.
2975         $markingallocationoptions = array();
2976         if ($markingallocation) {
2977             $markers = get_users_by_capability($this->context, 'mod/assign:grade');
2978             $markingallocationoptions[''] = get_string('filternone', 'assign');
2979             foreach ($markers as $marker) {
2980                 $markingallocationoptions[$marker->id] = fullname($marker);
2981             }
2982         }
2984         $markingworkflow = $this->get_instance()->markingworkflow;
2985         // Get marking states to show in form.
2986         $markingworkflowoptions = array();
2987         if ($markingworkflow) {
2988             $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
2989             $markingworkflowoptions[''] = get_string('filternone', 'assign');
2990             $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
2991             $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
2992         }
2994         // Print options for changing the filter and changing the number of results per page.
2995         $gradingoptionsformparams = array('cm'=>$cmid,
2996                                           'contextid'=>$this->context->id,
2997                                           'userid'=>$USER->id,
2998                                           'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2999                                           'showquickgrading'=>$showquickgrading,
3000                                           'quickgrading'=>$quickgrading,
3001                                           'markingworkflowopt'=>$markingworkflowoptions,
3002                                           'markingallocationopt'=>$markingallocationoptions,
3003                                           'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
3004                                           'showonlyactiveenrol'=>$this->show_only_active_users());
3006         $classoptions = array('class'=>'gradingoptionsform');
3007         $gradingoptionsform = new mod_assign_grading_options_form(null,
3008                                                                   $gradingoptionsformparams,
3009                                                                   'post',
3010                                                                   '',
3011                                                                   $classoptions);
3013         $batchformparams = array('cm'=>$cmid,
3014                                  'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3015                                  'duedate'=>$this->get_instance()->duedate,
3016                                  'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3017                                  'feedbackplugins'=>$this->get_feedback_plugins(),
3018                                  'context'=>$this->get_context(),
3019                                  'markingworkflow'=>$markingworkflow,
3020                                  'markingallocation'=>$markingallocation);
3021         $classoptions = array('class'=>'gradingbatchoperationsform');
3023         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
3024                                                                                    $batchformparams,
3025                                                                                    'post',
3026                                                                                    '',
3027                                                                                    $classoptions);
3029         $gradingoptionsdata = new stdClass();
3030         $gradingoptionsdata->perpage = $perpage;
3031         $gradingoptionsdata->filter = $filter;
3032         $gradingoptionsdata->markerfilter = $markerfilter;
3033         $gradingoptionsdata->workflowfilter = $workflowfilter;
3034         $gradingoptionsform->set_data($gradingoptionsdata);
3036         $actionformtext = $this->get_renderer()->render($gradingactions);
3037         $header = new assign_header($this->get_instance(),
3038                                     $this->get_context(),
3039                                     false,
3040                                     $this->get_course_module()->id,
3041                                     get_string('grading', 'assign'),
3042                                     $actionformtext);
3043         $o .= $this->get_renderer()->render($header);
3045         $currenturl = $CFG->wwwroot .
3046                       '/mod/assign/view.php?id=' .
3047                       $this->get_course_module()->id .
3048                       '&action=grading';
3050         $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3052         // Plagiarism update status apearring in the grading book.
3053         if (!empty($CFG->enableplagiarism)) {
3054             require_once($CFG->libdir . '/plagiarismlib.php');
3055             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
3056         }
3058         // Load and print the table of submissions.
3059         if ($showquickgrading && $quickgrading) {
3060             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3061             $table = $this->get_renderer()->render($gradingtable);
3062             $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
3063             $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3065             $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3066         } else {
3067             $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3068             $o .= $this->get_renderer()->render($gradingtable);
3069         }
3071         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3072         $users = array_keys($this->list_participants($currentgroup, true));
3073         if (count($users) != 0) {
3074             // If no enrolled user in a course then don't display the batch operations feature.
3075             $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3076             $o .= $this->get_renderer()->render($assignform);
3077         }
3078         $assignform = new assign_form('gradingoptionsform',
3079                                       $gradingoptionsform,
3080                                       'M.mod_assign.init_grading_options');
3081         $o .= $this->get_renderer()->render($assignform);
3082         return $o;
3083     }
3085     /**
3086      * View entire grading page.
3087      *
3088      * @return string
3089      */
3090     protected function view_grading_page() {
3091         global $CFG;
3093         $o = '';
3094         // Need submit permission to submit an assignment.
3095         require_capability('mod/assign:grade', $this->context);
3096         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3098         // Only load this if it is.
3100         $o .= $this->view_grading_table();
3102         $o .= $this->view_footer();
3104         $logmessage = get_string('viewsubmissiongradingtable', 'assign');
3105         $this->add_to_log('view submission grading table', $logmessage);
3106         return $o;
3107     }
3109     /**
3110      * Capture the output of the plagiarism plugins disclosures and return it as a string.
3111      *
3112      * @return void
3113      */
3114     protected function plagiarism_print_disclosure() {
3115         global $CFG;
3116         $o = '';
3118         if (!empty($CFG->enableplagiarism)) {
3119             require_once($CFG->libdir . '/plagiarismlib.php');
3121             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3122         }
3124         return $o;
3125     }
3127     /**
3128      * Message for students when assignment submissions have been closed.
3129      *
3130      * @return string
3131      */
3132     protected function view_student_error_message() {
3133         global $CFG;
3135         $o = '';
3136         // Need submit permission to submit an assignment.
3137         require_capability('mod/assign:submit', $this->context);
3139         $header = new assign_header($this->get_instance(),
3140                                     $this->get_context(),
3141                                     $this->show_intro(),
3142                                     $this->get_course_module()->id,
3143                                     get_string('editsubmission', 'assign'));
3144         $o .= $this->get_renderer()->render($header);
3146         $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
3148         $o .= $this->view_footer();
3150         return $o;
3152     }
3154     /**
3155      * View edit submissions page.
3156      *
3157      * @param moodleform $mform
3158      * @param array $notices A list of notices to display at the top of the
3159      *                       edit submission form (e.g. from plugins).
3160      * @return string The page output.
3161      */
3162     protected function view_edit_submission_page($mform, $notices) {
3163         global $CFG;
3165         $o = '';
3166         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
3167         // Need submit permission to submit an assignment.
3168         require_capability('mod/assign:submit', $this->context);
3170         if (!$this->submissions_open()) {
3171             return $this->view_student_error_message();
3172         }
3173         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3174                                                       $this->get_context(),
3175                                                       $this->show_intro(),
3176                                                       $this->get_course_module()->id,
3177                                                       get_string('editsubmission', 'assign')));
3178         $o .= $this->plagiarism_print_disclosure();
3179         $data = new stdClass();
3181         if (!$mform) {
3182             $mform = new mod_assign_submission_form(null, array($this, $data));
3183         }
3185         foreach ($notices as $notice) {
3186             $o .= $this->get_renderer()->notification($notice);
3187         }
3189         $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
3191         $o .= $this->view_footer();
3192         $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
3194         return $o;
3195     }
3197     /**
3198      * See if this assignment has a grade yet.
3199      *
3200      * @param int $userid
3201      * @return bool
3202      */
3203     protected function is_graded($userid) {
3204         $grade = $this->get_user_grade($userid, false);
3205         if ($grade) {
3206             return ($grade->grade !== null && $grade->grade >= 0);
3207         }
3208         return false;
3209     }
3211     /**
3212      * Perform an access check to see if the current $USER can view this group submission.
3213      *
3214      * @param int $groupid
3215      * @return bool
3216      */
3217     public function can_view_group_submission($groupid) {
3218         global $USER;
3220         if (has_capability('mod/assign:grade', $this->context)) {
3221             return true;
3222         }
3223         if (!is_enrolled($this->get_course_context(), $USER->id)) {
3224             return false;
3225         }
3226         $members = $this->get_submission_group_members($groupid, true);
3227         foreach ($members as $member) {
3228             if ($member->id == $USER->id) {
3229                 return true;
3230             }
3231         }
3232         return false;
3233     }
3235     /**
3236      * Perform an access check to see if the current $USER can view this users submission.
3237      *
3238      * @param int $userid
3239      * @return bool
3240      */
3241     public function can_view_submission($userid) {
3242         global $USER;
3244         if (!$this->is_active_user($userid) && !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
3245             return false;
3246         }
3247         if (has_capability('mod/assign:grade', $this->context)) {
3248             return true;
3249         }
3250         if (!is_enrolled($this->get_course_context(), $userid)) {
3251             return false;
3252         }
3253         if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
3254             return true;
3255         }
3256         return false;
3257     }
3259     /**
3260      * Allows the plugin to show a batch grading operation page.
3261      *
3262      * @param moodleform $mform
3263      * @return none
3264      */
3265     protected function view_plugin_grading_batch_operation($mform) {