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