Merge branch 'MDL-30700-23' of git://github.com/damyon/moodle into MOODLE_23_STABLE
[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 /**
30  * Assignment submission statuses
31  */
32 define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft'); // student thinks it is a draft
33 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted'); // student thinks it is finished
35 /**
36  * Search filters for grading page
37  */
38 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
39 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
40 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
42 /** Include accesslib.php */
43 require_once($CFG->libdir.'/accesslib.php');
44 /** Include formslib.php */
45 require_once($CFG->libdir.'/formslib.php');
46 /** Include repository/lib.php */
47 require_once($CFG->dirroot . '/repository/lib.php');
48 /** Include local mod_form.php */
49 require_once($CFG->dirroot.'/mod/assign/mod_form.php');
50 /** gradelib.php */
51 require_once($CFG->libdir.'/gradelib.php');
52 /** grading lib.php */
53 require_once($CFG->dirroot.'/grade/grading/lib.php');
54 /** Include feedbackplugin.php */
55 require_once($CFG->dirroot.'/mod/assign/feedbackplugin.php');
56 /** Include submissionplugin.php */
57 require_once($CFG->dirroot.'/mod/assign/submissionplugin.php');
58 /** Include renderable.php */
59 require_once($CFG->dirroot.'/mod/assign/renderable.php');
60 /** Include gradingtable.php */
61 require_once($CFG->dirroot.'/mod/assign/gradingtable.php');
62 /** Include eventslib.php */
63 require_once($CFG->libdir.'/eventslib.php');
66 /**
67  * Standard base class for mod_assign (assignment types).
68  *
69  * @package   mod_assign
70  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
71  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
72  */
73 class assign {
76     /** @var stdClass the assignment record that contains the global settings for this assign instance */
77     private $instance;
79     /** @var context the context of the course module for this assign instance (or just the course if we are
80         creating a new one) */
81     private $context;
83     /** @var stdClass the course this assign instance belongs to */
84     private $course;
86     /** @var stdClass the admin config for all assign instances  */
87     private $adminconfig;
90     /** @var assign_renderer the custom renderer for this module */
91     private $output;
93     /** @var stdClass the course module for this assign instance */
94     private $coursemodule;
96     /** @var array cache for things like the coursemodule name or the scale menu - only lives for a single
97         request */
98     private $cache;
100     /** @var array list of the installed submission plugins */
101     private $submissionplugins;
103     /** @var array list of the installed feedback plugins */
104     private $feedbackplugins;
106     /** @var string action to be used to return to this page (without repeating any form submissions etc.) */
107     private $returnaction = 'view';
109     /** @var array params to be used to return to this page */
110     private $returnparams = array();
112     /** @var string modulename prevents excessive calls to get_string */
113     private static $modulename = null;
115     /** @var string modulenameplural prevents excessive calls to get_string */
116     private static $modulenameplural = null;
118     /**
119      * Constructor for the base assign class
120      *
121      * @param mixed $coursemodulecontext context|null the course module context (or the course context if the coursemodule has not been created yet)
122      * @param mixed $coursemodule the current course module if it was already loaded - otherwise this class will load one from the context as required
123      * @param mixed $course the current course  if it was already loaded - 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;
131         $this->cache = array(); // temporary cache only lives for a single request - used to reduce db lookups
133         $this->submissionplugins = $this->load_plugins('assignsubmission');
134         $this->feedbackplugins = $this->load_plugins('assignfeedback');
135         $this->output = $PAGE->get_renderer('mod_assign');
136     }
138     /**
139      * Set the action and parameters that can be used to return to the current page
140      *
141      * @param string $action The action for the current page
142      * @param array $params An array of name value pairs which form the parameters to return to the current page
143      * @return void
144      */
145     public function register_return_link($action, $params) {
146         $this->returnaction = $action;
147         $this->returnparams = $params;
148     }
150     /**
151      * Return an action that can be used to get back to the current page
152      * @return string action
153      */
154     public function get_return_action() {
155         return $this->returnaction;
156     }
158     /**
159      * Based on the current assignment settings should we display the intro
160      * @return bool showintro
161      */
162     private function show_intro() {
163         if ($this->get_instance()->alwaysshowdescription ||
164                 time() > $this->get_instance()->allowsubmissionsfromdate) {
165             return true;
166         }
167         return false;
168     }
170     /**
171      * Return a list of parameters that can be used to get back to the current page
172      * @return array params
173      */
174     public function get_return_params() {
175         return $this->returnparams;
176     }
178     /**
179      * Set the submitted form data
180      * @param stdClass $data The form data (instance)
181      */
182     public function set_instance(stdClass $data) {
183         $this->instance = $data;
184     }
186     /**
187      * Set the context
188      * @param context $context The new context
189      */
190     public function set_context(context $context) {
191         $this->context = $context;
192     }
194     /**
195      * Set the course data
196      * @param stdClass $course The course data
197      */
198     public function set_course(stdClass $course) {
199         $this->course = $course;
200     }
202     /**
203      * get list of feedback plugins installed
204      * @return array
205      */
206     public function get_feedback_plugins() {
207         return $this->feedbackplugins;
208     }
210     /**
211      * get list of submission plugins installed
212      * @return array
213      */
214     public function get_submission_plugins() {
215         return $this->submissionplugins;
216     }
219     /**
220      * get a specific submission plugin by its type
221      * @param string $subtype assignsubmission | assignfeedback
222      * @param string $type
223      * @return mixed assign_plugin|null
224      */
225     private function get_plugin_by_type($subtype, $type) {
226         $shortsubtype = substr($subtype, strlen('assign'));
227         $name = $shortsubtype . 'plugins';
228         $pluginlist = $this->$name;
229         foreach ($pluginlist as $plugin) {
230             if ($plugin->get_type() == $type) {
231                 return $plugin;
232             }
233         }
234         return null;
235     }
237     /**
238      * Get a feedback plugin by type
239      * @param string $type - The type of plugin e.g comments
240      * @return mixed assign_feedback_plugin|null
241      */
242     public function get_feedback_plugin_by_type($type) {
243         return $this->get_plugin_by_type('assignfeedback', $type);
244     }
246     /**
247      * Get a submission plugin by type
248      * @param string $type - The type of plugin e.g comments
249      * @return mixed assign_submission_plugin|null
250      */
251     public function get_submission_plugin_by_type($type) {
252         return $this->get_plugin_by_type('assignsubmission', $type);
253     }
255     /**
256      * Load the plugins from the sub folders under subtype
257      * @param string $subtype - either submission or feedback
258      * @return array - The sorted list of plugins
259      */
260     private function load_plugins($subtype) {
261         global $CFG;
262         $result = array();
264         $names = get_plugin_list($subtype);
266         foreach ($names as $name => $path) {
267             if (file_exists($path . '/locallib.php')) {
268                 require_once($path . '/locallib.php');
270                 $shortsubtype = substr($subtype, strlen('assign'));
271                 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
273                 $plugin = new $pluginclass($this, $name);
275                 if ($plugin instanceof assign_plugin) {
276                     $idx = $plugin->get_sort_order();
277                     while (array_key_exists($idx, $result)) $idx +=1;
278                     $result[$idx] = $plugin;
279                 }
280             }
281         }
282         ksort($result);
283         return $result;
284     }
287     /**
288      * Display the assignment, used by view.php
289      *
290      * The assignment is displayed differently depending on your role,
291      * the settings for the assignment and the status of the assignment.
292      * @param string $action The current action if any.
293      * @return void
294      */
295     public function view($action='') {
297         $o = '';
298         $mform = null;
299         $notices = array();
301         // Handle form submissions first.
302         if ($action == 'savesubmission') {
303             $action = 'editsubmission';
304             if ($this->process_save_submission($mform, $notices)) {
305                 $action = 'view';
306             }
307          } else if ($action == 'lock') {
308             $this->process_lock();
309             $action = 'grading';
310          } else if ($action == 'reverttodraft') {
311             $this->process_revert_to_draft();
312             $action = 'grading';
313          } else if ($action == 'unlock') {
314             $this->process_unlock();
315             $action = 'grading';
316          } else if ($action == 'confirmsubmit') {
317             $this->process_submit_for_grading();
318             // save and show next button
319          } else if ($action == 'batchgradingoperation') {
320             $this->process_batch_grading_operation();
321             $action = 'grading';
322          } else if ($action == 'submitgrade') {
323             if (optional_param('saveandshownext', null, PARAM_RAW)) {
324                 //save and show next
325                 $action = 'grade';
326                 if ($this->process_save_grade($mform)) {
327                     $action = 'nextgrade';
328                 }
329             } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
330                 $action = 'previousgrade';
331             } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
332                 //show next button
333                 $action = 'nextgrade';
334             } else if (optional_param('savegrade', null, PARAM_RAW)) {
335                 //save changes button
336                 $action = 'grade';
337                 if ($this->process_save_grade($mform)) {
338                     $action = 'grading';
339                 }
340             } else {
341                 //cancel button
342                 $action = 'grading';
343             }
344         }else if ($action == 'quickgrade') {
345             $message = $this->process_save_quick_grades();
346             $action = 'quickgradingresult';
347         }else if ($action == 'saveoptions') {
348             $this->process_save_grading_options();
349             $action = 'grading';
350         }
352         $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT));
353         $this->register_return_link($action, $returnparams);
355         // Now show the right view page.
356         if ($action == 'previousgrade') {
357             $mform = null;
358             $o .= $this->view_single_grade_page($mform, -1);
359         } else if ($action == 'quickgradingresult') {
360             $mform = null;
361             $o .= $this->view_quickgrading_result($message);
362         } else if ($action == 'nextgrade') {
363             $mform = null;
364             $o .= $this->view_single_grade_page($mform, 1);
365         } else if ($action == 'grade') {
366             $o .= $this->view_single_grade_page($mform);
367         } else if ($action == 'viewpluginassignfeedback') {
368             $o .= $this->view_plugin_content('assignfeedback');
369         } else if ($action == 'viewpluginassignsubmission') {
370             $o .= $this->view_plugin_content('assignsubmission');
371         } else if ($action == 'editsubmission') {
372             $o .= $this->view_edit_submission_page($mform, $notices);
373         } else if ($action == 'grading') {
374             $o .= $this->view_grading_page();
375         } else if ($action == 'downloadall') {
376             $o .= $this->download_submissions();
377         } else if ($action == 'submit') {
378             $o .= $this->check_submit_for_grading();
379         } else {
380             $o .= $this->view_submission_page();
381         }
383         return $o;
384     }
387     /**
388      * Add this instance to the database
389      *
390      * @param stdClass $formdata The data submitted from the form
391      * @param bool $callplugins This is used to skip the plugin code
392      *             when upgrading an old assignment to a new one (the plugins get called manually)
393      * @return mixed false if an error occurs or the int id of the new instance
394      */
395     public function add_instance(stdClass $formdata, $callplugins) {
396         global $DB;
398         $err = '';
400         // add the database record
401         $update = new stdClass();
402         $update->name = $formdata->name;
403         $update->timemodified = time();
404         $update->timecreated = time();
405         $update->course = $formdata->course;
406         $update->courseid = $formdata->course;
407         $update->intro = $formdata->intro;
408         $update->introformat = $formdata->introformat;
409         $update->alwaysshowdescription = $formdata->alwaysshowdescription;
410         $update->preventlatesubmissions = $formdata->preventlatesubmissions;
411         $update->submissiondrafts = $formdata->submissiondrafts;
412         $update->sendnotifications = $formdata->sendnotifications;
413         $update->sendlatenotifications = $formdata->sendlatenotifications;
414         $update->duedate = $formdata->duedate;
415         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
416         $update->grade = $formdata->grade;
417         $returnid = $DB->insert_record('assign', $update);
418         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
419         // cache the course record
420         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
422         if ($callplugins) {
423             // call save_settings hook for submission plugins
424             foreach ($this->submissionplugins as $plugin) {
425                 if (!$this->update_plugin_instance($plugin, $formdata)) {
426                     print_error($plugin->get_error());
427                     return false;
428                 }
429             }
430             foreach ($this->feedbackplugins as $plugin) {
431                 if (!$this->update_plugin_instance($plugin, $formdata)) {
432                     print_error($plugin->get_error());
433                     return false;
434                 }
435             }
437             // in the case of upgrades the coursemodule has not been set so we need to wait before calling these two
438             // TODO: add event to the calendar
439             $this->update_calendar($formdata->coursemodule);
440             // TODO: add the item in the gradebook
441             $this->update_gradebook(false, $formdata->coursemodule);
443         }
445         $update = new stdClass();
446         $update->id = $this->get_instance()->id;
447         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
448         $DB->update_record('assign', $update);
450         return $returnid;
451     }
453     /**
454      * Delete all grades from the gradebook for this assignment
455      *
456      * @return bool
457      */
458     private function delete_grades() {
459         global $CFG;
461         return grade_update('mod/assign', $this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, 0, NULL, array('deleted'=>1)) == GRADE_UPDATE_OK;
462     }
464     /**
465      * Delete this instance from the database
466      *
467      * @return bool false if an error occurs
468      */
469     public function delete_instance() {
470         global $DB;
471         $result = true;
473         foreach ($this->submissionplugins as $plugin) {
474             if (!$plugin->delete_instance()) {
475                 print_error($plugin->get_error());
476                 $result = false;
477             }
478         }
479         foreach ($this->feedbackplugins as $plugin) {
480             if (!$plugin->delete_instance()) {
481                 print_error($plugin->get_error());
482                 $result = false;
483             }
484         }
486         // delete files associated with this assignment
487         $fs = get_file_storage();
488         if (! $fs->delete_area_files($this->context->id) ) {
489             $result = false;
490         }
492         // delete_records will throw an exception if it fails - so no need for error checking here
494         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
495         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
496         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
498         // delete items from the gradebook
499         if (! $this->delete_grades()) {
500             $result = false;
501         }
503         // delete the instance
504         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
506         return $result;
507     }
509     /**
510     * Actual implementation of the reset course functionality, delete all the
511     * assignment submissions for course $data->courseid.
512     *
513     * @param $data the data submitted from the reset course.
514     * @return array status array
515     */
516     public function reset_userdata($data) {
517         global $CFG,$DB;
519         $componentstr = get_string('modulenameplural', 'assign');
520         $status = array();
522         $fs = get_file_storage();
523         if (!empty($data->reset_assign_submissions)) {
524             // Delete files associated with this assignment.
525             foreach ($this->submissionplugins as $plugin) {
526                 $fileareas = array();
527                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
528                 $fileareas = $plugin->get_file_areas();
529                 foreach ($fileareas as $filearea) {
530                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
531                 }
533                 if (!$plugin->delete_instance()) {
534                     $status[] = array('component'=>$componentstr,
535                                       'item'=>get_string('deleteallsubmissions','assign'),
536                                       'error'=>$plugin->get_error());
537                 }
538             }
540             foreach ($this->feedbackplugins as $plugin) {
541                 $fileareas = array();
542                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
543                 $fileareas = $plugin->get_file_areas();
544                 foreach ($fileareas as $filearea) {
545                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
546                 }
548                 if (!$plugin->delete_instance()) {
549                     $status[] = array('component'=>$componentstr,
550                                       'item'=>get_string('deleteallsubmissions','assign'),
551                                       'error'=>$plugin->get_error());
552                 }
553             }
555             $assignssql = "SELECT a.id
556                              FROM {assign} a
557                            WHERE a.course=:course";
558             $params = array ("course" => $data->courseid);
560             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
561             $status[] = array('component'=>$componentstr,
562                               'item'=>get_string('deleteallsubmissions','assign'),
563                               'error'=>false);
565             if (empty($data->reset_gradebook_grades)) {
566                 // Remove all grades from gradebook.
567                 require_once($CFG->dirroot.'/mod/assign/lib.php');
568                 assign_reset_gradebook($data->courseid);
569             }
570         }
571         // Updating dates - shift may be negative too.
572         if ($data->timeshift) {
573             shift_course_mod_dates('assign',
574                                     array('duedate', 'allowsubmissionsfromdate'),
575                                     $data->timeshift,
576                                     $data->courseid);
577             $status[] = array('component'=>$componentstr,
578                               'item'=>get_string('datechanged'),
579                               'error'=>false);
580         }
582         return $status;
583     }
585     /**
586      * Update the settings for a single plugin
587      *
588      * @param assign_plugin $plugin The plugin to update
589      * @param stdClass $formdata The form data
590      * @return bool false if an error occurs
591      */
592     private function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
593         if ($plugin->is_visible()) {
594             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
595             if ($formdata->$enabledname) {
596                 $plugin->enable();
597                 if (!$plugin->save_settings($formdata)) {
598                     print_error($plugin->get_error());
599                     return false;
600                 }
601             } else {
602                 $plugin->disable();
603             }
604         }
605         return true;
606     }
608     /**
609      * Update the gradebook information for this assignment
610      *
611      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
612      * @param int $coursemoduleid This is required because it might not exist in the database yet
613      * @return bool
614      */
615     public function update_gradebook($reset, $coursemoduleid) {
616          global $CFG;
617         /** Include lib.php */
618         require_once($CFG->dirroot.'/mod/assign/lib.php');
619         $assign = clone $this->get_instance();
620         $assign->cmidnumber = $coursemoduleid;
621         $param = null;
622         if ($reset) {
623             $param = 'reset';
624         }
626         return assign_grade_item_update($assign, $param);
627     }
629     /** Load and cache the admin config for this module
630      *
631      * @return stdClass the plugin config
632      */
633     public function get_admin_config() {
634         if ($this->adminconfig) {
635             return $this->adminconfig;
636         }
637         $this->adminconfig = get_config('assign');
638         return $this->adminconfig;
639     }
642     /**
643      * Update the calendar entries for this assignment
644      *
645      * @param int $coursemoduleid - Required to pass this in because it might not exist in the database yet
646      * @return bool
647      */
648     public function update_calendar($coursemoduleid) {
649         global $DB, $CFG;
650         require_once($CFG->dirroot.'/calendar/lib.php');
652         // special case for add_instance as the coursemodule has not been set yet.
654         if ($this->get_instance()->duedate) {
655             $event = new stdClass();
657             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id))) {
659                 $event->name        = $this->get_instance()->name;
661                 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
662                 $event->timestart   = $this->get_instance()->duedate;
664                 $calendarevent = calendar_event::load($event->id);
665                 $calendarevent->update($event);
666             } else {
667                 $event = new stdClass();
668                 $event->name        = $this->get_instance()->name;
669                 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
670                 $event->courseid    = $this->get_instance()->course;
671                 $event->groupid     = 0;
672                 $event->userid      = 0;
673                 $event->modulename  = 'assign';
674                 $event->instance    = $this->get_instance()->id;
675                 $event->eventtype   = 'due';
676                 $event->timestart   = $this->get_instance()->duedate;
677                 $event->timeduration = 0;
679                 calendar_event::create($event);
680             }
681         } else {
682             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id));
683         }
684     }
687     /**
688      * Update this instance in the database
689      *
690      * @param stdClass $formdata - the data submitted from the form
691      * @return bool false if an error occurs
692      */
693     public function update_instance($formdata) {
694         global $DB;
696         $update = new stdClass();
697         $update->id = $formdata->instance;
698         $update->name = $formdata->name;
699         $update->timemodified = time();
700         $update->course = $formdata->course;
701         $update->intro = $formdata->intro;
702         $update->introformat = $formdata->introformat;
703         $update->alwaysshowdescription = $formdata->alwaysshowdescription;
704         $update->preventlatesubmissions = $formdata->preventlatesubmissions;
705         $update->submissiondrafts = $formdata->submissiondrafts;
706         $update->sendnotifications = $formdata->sendnotifications;
707         $update->sendlatenotifications = $formdata->sendlatenotifications;
708         $update->duedate = $formdata->duedate;
709         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
710         $update->grade = $formdata->grade;
712         $result = $DB->update_record('assign', $update);
713         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
715         // load the assignment so the plugins have access to it
717         // call save_settings hook for submission plugins
718         foreach ($this->submissionplugins as $plugin) {
719             if (!$this->update_plugin_instance($plugin, $formdata)) {
720                 print_error($plugin->get_error());
721                 return false;
722             }
723         }
724         foreach ($this->feedbackplugins as $plugin) {
725             if (!$this->update_plugin_instance($plugin, $formdata)) {
726                 print_error($plugin->get_error());
727                 return false;
728             }
729         }
732         // update the database record
735         // update all the calendar events
736         $this->update_calendar($this->get_course_module()->id);
738         $this->update_gradebook(false, $this->get_course_module()->id);
740         $update = new stdClass();
741         $update->id = $this->get_instance()->id;
742         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
743         $DB->update_record('assign', $update);
749         return $result;
750     }
752     /**
753      * add elements in grading plugin form
754      *
755      * @param mixed $grade stdClass|null
756      * @param MoodleQuickForm $mform
757      * @param stdClass $data
758      * @param int $userid - The userid we are grading
759      * @return void
760      */
761     private function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
762         foreach ($this->feedbackplugins as $plugin) {
763             if ($plugin->is_enabled() && $plugin->is_visible()) {
764                 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
765                 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
766                     $mform->removeElement('header_' . $plugin->get_type());
767                 }
768             }
769         }
770     }
774     /**
775      * Add one plugins settings to edit plugin form
776      *
777      * @param assign_plugin $plugin The plugin to add the settings from
778      * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
779      * @return void
780      */
781     private function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform) {
782         global $CFG;
783         if ($plugin->is_visible()) {
784             // enabled
785             //tied disableIf rule to this select element
786             $mform->addElement('selectyesno', $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $plugin->get_name());
787             $mform->addHelpButton($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', 'enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
790             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
791             if ($plugin->get_config('enabled') !== false) {
792                 $default = $plugin->is_enabled();
793             }
794             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
796             $plugin->get_settings($mform);
798         }
800     }
803     /**
804      * Add settings to edit plugin form
805      *
806      * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
807      * @return void
808      */
809     public function add_all_plugin_settings(MoodleQuickForm $mform) {
810         $mform->addElement('header', 'general', get_string('submissionsettings', 'assign'));
812         foreach ($this->submissionplugins as $plugin) {
813             $this->add_plugin_settings($plugin, $mform);
815         }
816         $mform->addElement('header', 'general', get_string('feedbacksettings', 'assign'));
817         foreach ($this->feedbackplugins as $plugin) {
818             $this->add_plugin_settings($plugin, $mform);
819         }
820     }
822     /**
823      * Allow each plugin an opportunity to update the defaultvalues
824      * passed in to the settings form (needed to set up draft areas for
825      * editor and filemanager elements)
826      * @param array $defaultvalues
827      */
828     public function plugin_data_preprocessing(&$defaultvalues) {
829         foreach ($this->submissionplugins as $plugin) {
830             if ($plugin->is_visible()) {
831                 $plugin->data_preprocessing($defaultvalues);
832             }
833         }
834         foreach ($this->feedbackplugins as $plugin) {
835             if ($plugin->is_visible()) {
836                 $plugin->data_preprocessing($defaultvalues);
837             }
838         }
839     }
841     /**
842      * Get the name of the current module.
843      *
844      * @return string the module name (Assignment)
845      */
846     protected function get_module_name() {
847         if (isset(self::$modulename)) {
848             return self::$modulename;
849         }
850         self::$modulename = get_string('modulename', 'assign');
851         return self::$modulename;
852     }
854     /**
855      * Get the plural name of the current module.
856      *
857      * @return string the module name plural (Assignments)
858      */
859     protected function get_module_name_plural() {
860         if (isset(self::$modulenameplural)) {
861             return self::$modulenameplural;
862         }
863         self::$modulenameplural = get_string('modulenameplural', 'assign');
864         return self::$modulenameplural;
865     }
867     /**
868      * Has this assignment been constructed from an instance?
869      *
870      * @return bool
871      */
872     public function has_instance() {
873         return $this->instance || $this->get_course_module();
874     }
876     /**
877      * Get the settings for the current instance of this assignment
878      *
879      * @return stdClass The settings
880      */
881     public function get_instance() {
882         global $DB;
883         if ($this->instance) {
884             return $this->instance;
885         }
886         if ($this->get_course_module()) {
887             $this->instance = $DB->get_record('assign', array('id' => $this->get_course_module()->instance), '*', MUST_EXIST);
888         }
889         if (!$this->instance) {
890             throw new coding_exception('Improper use of the assignment class. Cannot load the assignment record.');
891         }
892         return $this->instance;
893     }
895     /**
896      * Get the context of the current course
897      * @return mixed context|null The course context
898      */
899     public function get_course_context() {
900         if (!$this->context && !$this->course) {
901             throw new coding_exception('Improper use of the assignment class. Cannot load the course context.');
902         }
903         if ($this->context) {
904             return $this->context->get_course_context();
905         } else {
906             return context_course::instance($this->course->id);
907         }
908     }
911     /**
912      * Get the current course module
913      *
914      * @return mixed stdClass|null The course module
915      */
916     public function get_course_module() {
917         if ($this->coursemodule) {
918             return $this->coursemodule;
919         }
920         if (!$this->context) {
921             return null;
922         }
924         if ($this->context->contextlevel == CONTEXT_MODULE) {
925             $this->coursemodule = get_coursemodule_from_id('assign', $this->context->instanceid, 0, false, MUST_EXIST);
926             return $this->coursemodule;
927         }
928         return null;
929     }
931     /**
932      * Get context module
933      *
934      * @return context
935      */
936     public function get_context() {
937         return $this->context;
938     }
940     /**
941      * Get the current course
942      * @return mixed stdClass|null The course
943      */
944     public function get_course() {
945         global $DB;
946         if ($this->course) {
947             return $this->course;
948         }
950         if (!$this->context) {
951             return null;
952         }
953         $this->course = $DB->get_record('course', array('id' => $this->get_course_context()->instanceid), '*', MUST_EXIST);
954         return $this->course;
955     }
957     /**
958      * Return a grade in user-friendly form, whether it's a scale or not
959      *
960      * @param mixed $grade int|null
961      * @param boolean $editing Are we allowing changes to this grade?
962      * @param int $userid The user id the grade belongs to
963      * @param int $modified Timestamp from when the grade was last modified
964      * @return string User-friendly representation of grade
965      */
966     public function display_grade($grade, $editing, $userid=0, $modified=0) {
967         global $DB;
969         static $scalegrades = array();
971         $o = '';
973         if ($this->get_instance()->grade >= 0) {
974             // Normal number
975             if ($editing && $this->get_instance()->grade > 0) {
976                 if ($grade < 0) {
977                     $displaygrade = '';
978                 } else {
979                     $displaygrade = format_float($grade);
980                 }
981                 $o .= '<input type="text" name="quickgrade_' . $userid . '" value="' . $displaygrade . '" size="6" maxlength="10" class="quickgrade"/>';
982                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade,2);
983                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
984                 return $o;
985             } else {
986                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
987                 if ($grade == -1 || $grade === null) {
988                     $o .= '-';
989                     return $o;
990                 } else {
991                     $o .= format_float(($grade),2) .'&nbsp;/&nbsp;'. format_float($this->get_instance()->grade,2);
992                     return $o;
993                 }
994             }
996         } else {
997             // Scale
998             if (empty($this->cache['scale'])) {
999                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1000                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1001                 } else {
1002                     $o .= '-';
1003                     return $o;
1004                 }
1005             }
1006             if ($editing) {
1007                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1008                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1009                 foreach ($this->cache['scale'] as $optionid => $option) {
1010                     $selected = '';
1011                     if ($grade == $optionid) {
1012                         $selected = 'selected="selected"';
1013                     }
1014                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1015                 }
1016                 $o .= '</select>';
1017                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1018                 return $o;
1019             } else {
1020                 $scaleid = (int)$grade;
1021                 if (isset($this->cache['scale'][$scaleid])) {
1022                     $o .= $this->cache['scale'][$scaleid];
1023                     return $o;
1024                 }
1025                 $o .= '-';
1026                 return $o;
1027             }
1028         }
1029     }
1031     /**
1032      * Load a list of users enrolled in the current course with the specified permission and group (0 for no group)
1033      *
1034      * @param int $currentgroup
1035      * @param bool $idsonly
1036      * @return array List of user records
1037      */
1038     public function list_participants($currentgroup, $idsonly) {
1039         if ($idsonly) {
1040             return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup, 'u.id');
1041         } else {
1042             return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1043         }
1044     }
1046     /**
1047      * Load a count of users enrolled in the current course with the specified permission and group (0 for no group)
1048      *
1049      * @param int $currentgroup
1050      * @return int number of matching users
1051      */
1052     public function count_participants($currentgroup) {
1053         return count_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1054     }
1056     /**
1057      * Load a count of users submissions in the current module that require grading
1058      * This means the submission modification time is more recent than the
1059      * grading modification time and the status is SUBMITTED.
1060      *
1061      * @return int number of matching submissions
1062      */
1063     public function count_submissions_need_grading() {
1064         global $DB;
1066         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1067         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1069         $params['assignid'] = $this->get_instance()->id;
1070         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1072         $sql = 'SELECT COUNT(s.userid)
1073                    FROM {assign_submission} s
1074                    LEFT JOIN {assign_grades} g ON
1075                         s.assignment = g.assignment AND
1076                         s.userid = g.userid
1077                    JOIN(' . $esql . ') AS e ON e.id = s.userid
1078                    WHERE
1079                         s.assignment = :assignid AND
1080                         s.timemodified IS NOT NULL AND
1081                         s.status = :submitted AND
1082                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1084         return $DB->count_records_sql($sql, $params);
1085     }
1087     /**
1088      * Load a count of users enrolled in the current course with the specified permission and group (optional)
1089      *
1090      * @param string $status The submission status - should match one of the constants
1091      * @return int number of matching submissions
1092      */
1093     public function count_submissions_with_status($status) {
1094         global $DB;
1096         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1097         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1099         $params['assignid'] = $this->get_instance()->id;
1100         $params['submissionstatus'] = $status;
1102         $sql = 'SELECT COUNT(s.userid)
1103                    FROM {assign_submission} s
1104                    LEFT JOIN {assign_grades} g ON
1105                         s.assignment = g.assignment AND
1106                         s.userid = g.userid
1107                    JOIN(' . $esql . ') AS e ON e.id = s.userid
1108                    WHERE
1109                         s.assignment = :assignid AND
1110                         s.timemodified IS NOT NULL AND
1111                         s.status = :submissionstatus AND
1112                         (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1114         return $DB->count_records_sql($sql, $params);
1115     }
1117     /**
1118      * Utility function to get the userid for every row in the grading table
1119      * so the order can be frozen while we iterate it
1120      *
1121      * @return array An array of userids
1122      */
1123     private function get_grading_userid_list(){
1124         $filter = get_user_preferences('assign_filter', '');
1125         $table = new assign_grading_table($this, 0, $filter, 0, false);
1127         $useridlist = $table->get_column_data('userid');
1129         return $useridlist;
1130     }
1133     /**
1134      * Utility function get the userid based on the row number of the grading table.
1135      * This takes into account any active filters on the table.
1136      *
1137      * @param int $num The row number of the user
1138      * @param bool $last This is set to true if this is the last user in the table
1139      * @return mixed The user id of the matching user or false if there was an error
1140      */
1141     private function get_userid_for_row($num, $last){
1142         if (!array_key_exists('userid_for_row', $this->cache)) {
1143             $this->cache['userid_for_row'] = array();
1144         }
1145         if (array_key_exists($num, $this->cache['userid_for_row'])) {
1146             list($userid, $last) = $this->cache['userid_for_row'][$num];
1147             return $userid;
1148         }
1150         $filter = get_user_preferences('assign_filter', '');
1151         $table = new assign_grading_table($this, 0, $filter, 0, false);
1153         $userid = $table->get_cell_data($num, 'userid', $last);
1155         $this->cache['userid_for_row'][$num] = array($userid, $last);
1156         return $userid;
1157     }
1159     /**
1160      * Return all assignment submissions by ENROLLED students (even empty)
1161      *
1162      * @param string $sort optional field names for the ORDER BY in the sql query
1163      * @param string $dir optional specifying the sort direction, defaults to DESC
1164      * @return array The submission objects indexed by id
1165      */
1166     private function get_all_submissions( $sort="", $dir="DESC") {
1167         global $DB;
1169         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1170         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1172         $params['assignid'] = $this->get_instance()->id;
1174         $sql = 'SELECT s.*, u.lastname, u.firstname, u.username
1175                    FROM {assign_submission} s
1176                    JOIN {user} u ON s.userid = u.id
1177                    JOIN(' . $esql . ') AS e ON e.id = s.userid
1178                    WHERE
1179                         s.assignment = :assignid AND
1180                         s.timemodified IS NOT NULL';
1182         if ($sort == "lastname" or $sort == "firstname") {
1183             $sort = "u.$sort $dir";
1184         } else if (empty($sort)) {
1185             $sort = "s.timemodified DESC";
1186         } else {
1187             $sort = "s.$sort $dir";
1188         }
1190         $sql .= ' ORDER BY ' . $sort;
1192         return $DB->get_records_sql($sql, $params);
1193     }
1195     /**
1196      * Generate zip file from array of given files
1197      *
1198      * @param array $filesforzipping - array of files to pass into archive_to_pathname - this array is indexed by the final file name and each element in the array is an instance of a stored_file object
1199      * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
1200      */
1201      private function pack_files($filesforzipping) {
1202          global $CFG;
1203          //create path for new zip file.
1204          $tempzip = tempnam($CFG->tempdir.'/', 'assignment_');
1205          //zip files
1206          $zipper = new zip_packer();
1207          if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1208              return $tempzip;
1209          }
1210          return false;
1211     }
1213     /**
1214      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1215      *
1216      * Cron function to be run periodically according to the moodle cron
1217      *
1218      * @return bool
1219      */
1220     static function cron() {
1221         global $DB;
1223         // only ever send a max of one days worth of updates
1224         $yesterday = time() - (24 * 3600);
1225         $timenow   = time();
1227         // Collect all submissions from the past 24 hours that require mailing.
1228         $sql = "SELECT s.*, a.course, a.name, g.*, g.id as gradeid, g.timemodified as lastmodified
1229                  FROM {assign} a
1230                  JOIN {assign_grades} g ON g.assignment = a.id
1231             LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1232                 WHERE g.timemodified >= :yesterday AND
1233                       g.timemodified <= :today AND
1234                       g.mailed = 0";
1235         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1236         $submissions = $DB->get_records_sql($sql, $params);
1238         if (empty($submissions)) {
1239             mtrace('done.');
1240             return true;
1241         }
1243         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1245         // Preload courses we are going to need those.
1246         $courseids = array();
1247         foreach ($submissions as $submission) {
1248             $courseids[] = $submission->course;
1249         }
1250         // Filter out duplicates
1251         $courseids = array_unique($courseids);
1252         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1253         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1254         $sql = "SELECT c.*, {$ctxselect}
1255                   FROM {course} c
1256              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1257                  WHERE c.id {$courseidsql}";
1258         $params['contextlevel'] = CONTEXT_COURSE;
1259         $courses = $DB->get_records_sql($sql, $params);
1260         // Clean up... this could go on for a while.
1261         unset($courseids);
1262         unset($ctxselect);
1263         unset($courseidsql);
1264         unset($params);
1266         // Simple array we'll use for caching modules.
1267         $modcache = array();
1269         // Message students about new feedback
1270         foreach ($submissions as $submission) {
1272             mtrace("Processing assignment submission $submission->id ...");
1274             // do not cache user lookups - could be too many
1275             if (!$user = $DB->get_record("user", array("id"=>$submission->userid))) {
1276                 mtrace("Could not find user $submission->userid");
1277                 continue;
1278             }
1280             // use a cache to prevent the same DB queries happening over and over
1281             if (!array_key_exists($submission->course, $courses)) {
1282                 mtrace("Could not find course $submission->course");
1283                 continue;
1284             }
1285             $course = $courses[$submission->course];
1286             if (isset($course->ctxid)) {
1287                 // Context has not yet been preloaded. Do so now.
1288                 context_helper::preload_from_record($course);
1289             }
1291             // Override the language and timezone of the "current" user, so that
1292             // mail is customised for the receiver.
1293             cron_setup_user($user, $course);
1295             // context lookups are already cached
1296             $coursecontext = context_course::instance($course->id);
1297             if (!is_enrolled($coursecontext, $user->id)) {
1298                 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
1299                 mtrace(fullname($user)." not an active participant in " . $courseshortname);
1300                 continue;
1301             }
1303             if (!$grader = $DB->get_record("user", array("id"=>$submission->grader))) {
1304                 mtrace("Could not find grader $submission->grader");
1305                 continue;
1306             }
1308             if (!array_key_exists($submission->assignment, $modcache)) {
1309                 if (! $mod = get_coursemodule_from_instance("assign", $submission->assignment, $course->id)) {
1310                     mtrace("Could not find course module for assignment id $submission->assignment");
1311                     continue;
1312                 }
1313                 $modcache[$submission->assignment] = $mod;
1314             } else {
1315                 $mod = $modcache[$submission->assignment];
1316             }
1317             // context lookups are already cached
1318             $contextmodule = context_module::instance($mod->id);
1320             if (!$mod->visible) {
1321                 // Hold mail notification for hidden assignments until later
1322                 continue;
1323             }
1325             // need to send this to the student
1326             $messagetype = 'feedbackavailable';
1327             $eventtype = 'assign_notification';
1328             $updatetime = $submission->lastmodified;
1329             $modulename = get_string('modulename', 'assign');
1330             self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime, $mod, $contextmodule, $course, $modulename, $submission->name);
1332             $grade = new stdClass();
1333             $grade->id = $submission->gradeid;
1334             $grade->mailed = 1;
1335             $DB->update_record('assign_grades', $grade);
1337             mtrace('Done');
1338         }
1339         mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1341         cron_setup_user();
1343         // Free up memory just to be sure
1344         unset($courses);
1345         unset($modcache);
1347         return true;
1348     }
1350     /**
1351      * Update a grade in the grade table for the assignment and in the gradebook
1352      *
1353      * @param stdClass $grade a grade record keyed on id
1354      * @return bool true for success
1355      */
1356     private function update_grade($grade) {
1357         global $DB;
1359         $grade->timemodified = time();
1361         if ($grade->grade && $grade->grade != -1) {
1362             if ($this->get_instance()->grade > 0) {
1363                 if (!is_numeric($grade->grade)) {
1364                     return false;
1365                 } else if ($grade->grade > $this->get_instance()->grade) {
1366                     return false;
1367                 } else if ($grade->grade < 0) {
1368                     return false;
1369                 }
1370             } else {
1371                 // this is a scale
1372                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1373                     $scaleoptions = make_menu_from_list($scale->scale);
1374                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1375                         return false;
1376                     }
1377                 }
1378             }
1379         }
1381         $result = $DB->update_record('assign_grades', $grade);
1382         if ($result) {
1383             $this->gradebook_item_update(null, $grade);
1384         }
1385         return $result;
1386     }
1388     /**
1389      * display the submission that is used by a plugin
1390      * Uses url parameters 'sid', 'gid' and 'plugin'
1391      * @param string $pluginsubtype
1392      * @return string
1393      */
1394     private function view_plugin_content($pluginsubtype) {
1395         global $USER;
1397         $o = '';
1399         $submissionid = optional_param('sid', 0, PARAM_INT);
1400         $gradeid = optional_param('gid', 0, PARAM_INT);
1401         $plugintype = required_param('plugin', PARAM_TEXT);
1402         $item = null;
1403         if ($pluginsubtype == 'assignsubmission') {
1404             $plugin = $this->get_submission_plugin_by_type($plugintype);
1405             if ($submissionid <= 0) {
1406                 throw new coding_exception('Submission id should not be 0');
1407             }
1408             $item = $this->get_submission($submissionid);
1410             // permissions
1411             if ($item->userid != $USER->id) {
1412                 require_capability('mod/assign:grade', $this->context);
1413             }
1414             $o .= $this->output->render(new assign_header($this->get_instance(),
1415                                                               $this->get_context(),
1416                                                               $this->show_intro(),
1417                                                               $this->get_course_module()->id,
1418                                                               $plugin->get_name()));
1419             $o .= $this->output->render(new assign_submission_plugin_submission($plugin,
1420                                                               $item,
1421                                                               assign_submission_plugin_submission::FULL,
1422                                                               $this->get_course_module()->id,
1423                                                               $this->get_return_action(),
1424                                                               $this->get_return_params()));
1426             $this->add_to_log('view submission', get_string('viewsubmissionforuser', 'assign', $item->userid));
1427         } else {
1428             $plugin = $this->get_feedback_plugin_by_type($plugintype);
1429             if ($gradeid <= 0) {
1430                 throw new coding_exception('Grade id should not be 0');
1431             }
1432             $item = $this->get_grade($gradeid);
1433             // permissions
1434             if ($item->userid != $USER->id) {
1435                 require_capability('mod/assign:grade', $this->context);
1436             }
1437             $o .= $this->output->render(new assign_header($this->get_instance(),
1438                                                               $this->get_context(),
1439                                                               $this->show_intro(),
1440                                                               $this->get_course_module()->id,
1441                                                               $plugin->get_name()));
1442             $o .= $this->output->render(new assign_feedback_plugin_feedback($plugin,
1443                                                               $item,
1444                                                               assign_feedback_plugin_feedback::FULL,
1445                                                               $this->get_course_module()->id,
1446                                                               $this->get_return_action(),
1447                                                               $this->get_return_params()));
1448             $this->add_to_log('view feedback', get_string('viewfeedbackforuser', 'assign', $item->userid));
1449         }
1452         $o .= $this->view_return_links();
1454         $o .= $this->view_footer();
1455         return $o;
1456     }
1458     /**
1459      * render the content in editor that is often used by plugin
1460      *
1461      * @param string $filearea
1462      * @param int  $submissionid
1463      * @param string $plugintype
1464      * @param string $editor
1465      * @param string $component
1466      * @return string
1467      */
1468     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1469         global $CFG;
1471         $result = '';
1473         $plugin = $this->get_submission_plugin_by_type($plugintype);
1475         $text = $plugin->get_editor_text($editor, $submissionid);
1476         $format = $plugin->get_editor_format($editor, $submissionid);
1478         $finaltext = file_rewrite_pluginfile_urls($text, 'pluginfile.php', $this->get_context()->id, $component, $filearea, $submissionid);
1479         $result .= format_text($finaltext, $format, array('overflowdiv' => true, 'context' => $this->get_context()));
1483         if ($CFG->enableportfolios) {
1484             require_once($CFG->libdir . '/portfoliolib.php');
1486             $button = new portfolio_add_button();
1487             $button->set_callback_options('assign_portfolio_caller', array('cmid' => $this->get_course_module()->id, 'sid' => $submissionid, 'plugin' => $plugintype, 'editor' => $editor, 'area'=>$filearea), '/mod/assign/portfolio_callback.php');
1488             $fs = get_file_storage();
1490             if ($files = $fs->get_area_files($this->context->id, $component,$filearea, $submissionid, "timemodified", false)) {
1491                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1492             } else {
1493                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1494             }
1495             $result .= $button->to_html();
1496         }
1497         return $result;
1498     }
1500     /**
1501      * Display a grading error
1502      *
1503      * @param string $message - The description of the result
1504      * @return string
1505      */
1506     private function view_quickgrading_result($message) {
1507         $o = '';
1508         $o .= $this->output->render(new assign_header($this->get_instance(),
1509                                                       $this->get_context(),
1510                                                       $this->show_intro(),
1511                                                       $this->get_course_module()->id,
1512                                                       get_string('quickgradingresult', 'assign')));
1513         $o .= $this->output->render(new assign_quickgrading_result($message, $this->get_course_module()->id));
1514         $o .= $this->view_footer();
1515         return $o;
1516     }
1518     /**
1519      * Display the page footer
1520      *
1521      * @return string
1522      */
1523     private function view_footer() {
1524         return $this->output->render_footer();
1525     }
1527     /**
1528      * Does this user have grade permission for this assignment
1529      *
1530      * @return bool
1531      */
1532     private function can_grade() {
1533         // Permissions check
1534         if (!has_capability('mod/assign:grade', $this->context)) {
1535             return false;
1536         }
1538         return true;
1539     }
1541     /**
1542      * Download a zip file of all assignment submissions
1543      *
1544      * @return void
1545      */
1546     private function download_submissions() {
1547         global $CFG,$DB;
1549         // more efficient to load this here
1550         require_once($CFG->libdir.'/filelib.php');
1552         // load all submissions
1553         $submissions = $this->get_all_submissions('','');
1555         if (empty($submissions)) {
1556             print_error('errornosubmissions', 'assign');
1557             return;
1558         }
1560         // build a list of files to zip
1561         $filesforzipping = array();
1562         $fs = get_file_storage();
1564         $groupmode = groups_get_activity_groupmode($this->get_course_module());
1565         $groupid = 0;   // All users
1566         $groupname = '';
1567         if ($groupmode) {
1568             $groupid = groups_get_activity_group($this->get_course_module(), true);
1569             $groupname = groups_get_group_name($groupid).'-';
1570         }
1572         // construct the zip file name
1573         $filename = str_replace(' ', '_', clean_filename($this->get_course()->shortname.'-'.$this->get_instance()->name.'-'.$groupname.$this->get_course_module()->id.".zip")); //name of new zip file.
1575         // get all the files for each submission
1576         foreach ($submissions as $submission) {
1577             $userid = $submission->userid; //get userid
1578             if ((groups_is_member($groupid,$userid) or !$groupmode or !$groupid)) {
1579                 // get the plugins to add their own files to the zip
1581                 $prefix = clean_filename(fullname($submission) . "_" .$userid . "_");
1583                 foreach ($this->submissionplugins as $plugin) {
1584                     if ($plugin->is_enabled() && $plugin->is_visible()) {
1585                         $pluginfiles = $plugin->get_files($submission);
1588                         foreach ($pluginfiles as $zipfilename => $file) {
1589                             $filesforzipping[$prefix . $zipfilename] = $file;
1590                         }
1591                     }
1592                 }
1594             }
1595         } // end of foreach loop
1596         if ($zipfile = $this->pack_files($filesforzipping)) {
1597             $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
1598             send_temp_file($zipfile, $filename); //send file and delete after sending.
1599         }
1600     }
1602     /**
1603      * Util function to add a message to the log
1604      *
1605      * @param string $action The current action
1606      * @param string $info A detailed description of the change. But no more than 255 characters.
1607      * @param string $url The url to the assign module instance.
1608      * @return void
1609      */
1610     public function add_to_log($action = '', $info = '', $url='') {
1611         global $USER;
1613         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
1614         if ($url != '') {
1615             $fullurl .= '&' . $url;
1616         }
1618         add_to_log($this->get_course()->id, 'assign', $action, $fullurl, $info, $this->get_course_module()->id, $USER->id);
1619     }
1621     /**
1622      * Load the submission object for a particular user, optionally creating it if required
1623      *
1624      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
1625      * @param bool $create optional Defaults to false. If set to true a new submission object will be created in the database
1626      * @return stdClass The submission
1627      */
1628     private function get_user_submission($userid, $create) {
1629         global $DB, $USER;
1631         if (!$userid) {
1632             $userid = $USER->id;
1633         }
1634         // if the userid is not null then use userid
1635         $submission = $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1637         if ($submission) {
1638             return $submission;
1639         }
1640         if ($create) {
1641             $submission = new stdClass();
1642             $submission->assignment   = $this->get_instance()->id;
1643             $submission->userid       = $userid;
1644             $submission->timecreated = time();
1645             $submission->timemodified = $submission->timecreated;
1646             $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1647             $sid = $DB->insert_record('assign_submission', $submission);
1648             $submission->id = $sid;
1649             return $submission;
1650         }
1651         return false;
1652     }
1654     /**
1655      * Load the submission object from it's id
1656      *
1657      * @param int $submissionid The id of the submission we want
1658      * @return stdClass The submission
1659      */
1660     private function get_submission($submissionid) {
1661         global $DB;
1663         return $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid), '*', MUST_EXIST);
1664     }
1666     /**
1667      * This will retrieve a grade object from the db, optionally creating it if required
1668      *
1669      * @param int $userid The user we are grading
1670      * @param bool $create If true the grade will be created if it does not exist
1671      * @return stdClass The grade record
1672      */
1673     private function get_user_grade($userid, $create) {
1674         global $DB, $USER;
1676         if (!$userid) {
1677             $userid = $USER->id;
1678         }
1680         // if the userid is not null then use userid
1681         $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1683         if ($grade) {
1684             return $grade;
1685         }
1686         if ($create) {
1687             $grade = new stdClass();
1688             $grade->assignment   = $this->get_instance()->id;
1689             $grade->userid       = $userid;
1690             $grade->timecreated = time();
1691             $grade->timemodified = $grade->timecreated;
1692             $grade->locked = 0;
1693             $grade->grade = -1;
1694             $grade->grader = $USER->id;
1695             $gid = $DB->insert_record('assign_grades', $grade);
1696             $grade->id = $gid;
1697             return $grade;
1698         }
1699         return false;
1700     }
1702     /**
1703      * This will retrieve a grade object from the db
1704      *
1705      * @param int $gradeid The id of the grade
1706      * @return stdClass The grade record
1707      */
1708     private function get_grade($gradeid) {
1709         global $DB;
1711         return $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid), '*', MUST_EXIST);
1712     }
1714     /**
1715      * Print the grading page for a single user submission
1716      *
1717      * @param moodleform $mform
1718      * @param int $offset
1719      * @return string
1720      */
1721     private function view_single_grade_page($mform, $offset=0) {
1722         global $DB, $CFG;
1724         $o = '';
1726         // Include grade form
1727         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1729         // Need submit permission to submit an assignment
1730         require_capability('mod/assign:grade', $this->context);
1732         $o .= $this->output->render(new assign_header($this->get_instance(),
1733                                                       $this->get_context(), false, $this->get_course_module()->id,get_string('grading', 'assign')));
1735         $rownum = required_param('rownum', PARAM_INT) + $offset;
1736         $useridlist = optional_param('useridlist', '', PARAM_TEXT);
1737         if ($useridlist) {
1738             $useridlist = explode(',', $useridlist);
1739         } else {
1740             $useridlist = $this->get_grading_userid_list();
1741         }
1742         $last = false;
1743         $userid = $useridlist[$rownum];
1744         if ($rownum == count($useridlist) - 1) {
1745             $last = true;
1746         }
1747         if (!$userid) {
1748             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
1749         }
1750         $user = $DB->get_record('user', array('id' => $userid));
1751         if ($user) {
1752             $o .= $this->output->render(new assign_user_summary($user, $this->get_course()->id, has_capability('moodle/site:viewfullnames', $this->get_course_context())));
1753         }
1754         $submission = $this->get_user_submission($userid, false);
1755         // get the current grade
1756         $grade = $this->get_user_grade($userid, false);
1757         if ($this->can_view_submission($userid)) {
1758             $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
1759             $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
1760                                                               $this->get_instance()->alwaysshowdescription,
1761                                                               $submission,
1762                                                               $this->is_any_submission_plugin_enabled(),
1763                                                               $gradelocked,
1764                                                               $this->is_graded($userid),
1765                                                               $this->get_instance()->duedate,
1766                                                               $this->get_submission_plugins(),
1767                                                               $this->get_return_action(),
1768                                                               $this->get_return_params(),
1769                                                               $this->get_course_module()->id,
1770                                                               assign_submission_status::GRADER_VIEW,
1771                                                               false,
1772                                                               false));
1773         }
1774         if ($grade) {
1775             $data = new stdClass();
1776             if ($grade->grade !== NULL && $grade->grade >= 0) {
1777                 $data->grade = format_float($grade->grade,2);
1778             }
1779         } else {
1780             $data = new stdClass();
1781             $data->grade = '';
1782         }
1784         // now show the grading form
1785         if (!$mform) {
1786             $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last)), 'post', '', array('class'=>'gradeform'));
1787         }
1788         $o .= $this->output->render(new assign_form('gradingform',$mform));
1790         $this->add_to_log('view grading form', get_string('viewgradingformforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
1792         $o .= $this->view_footer();
1793         return $o;
1794     }
1798     /**
1799      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
1800      *
1801      * @return string
1802      */
1803     private function view_return_links() {
1805         $returnaction = optional_param('returnaction','', PARAM_ALPHA);
1806         $returnparams = optional_param('returnparams','', PARAM_TEXT);
1808         $params = array();
1809         parse_str($returnparams, $params);
1810         $params = array_merge( array('id' => $this->get_course_module()->id, 'action' => $returnaction), $params);
1812         return $this->output->single_button(new moodle_url('/mod/assign/view.php', $params), get_string('back'), 'get');
1814     }
1816     /**
1817      * View the grading table of all submissions for this assignment
1818      *
1819      * @return string
1820      */
1821     private function view_grading_table() {
1822         global $USER, $CFG;
1823         // Include grading options form
1824         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
1825         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
1826         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1827         $o = '';
1829         $links = array();
1830         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
1831                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
1832             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
1833             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
1834         }
1835         if ($this->is_any_submission_plugin_enabled()) {
1836             $downloadurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=downloadall';
1837             $links[$downloadurl] = get_string('downloadall', 'assign');
1838         }
1840         $gradingactions = new url_select($links);
1841         $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
1843         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
1845         $perpage = get_user_preferences('assign_perpage', 10);
1846         $filter = get_user_preferences('assign_filter', '');
1847         $controller = $gradingmanager->get_active_controller();
1848         $showquickgrading = empty($controller);
1849         if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
1850             $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
1851             set_user_preference('assign_quickgrading', $quickgrading);
1852         }
1853         $quickgrading = get_user_preferences('assign_quickgrading', false);
1855         // print options  for changing the filter and changing the number of results per page
1856         $gradingoptionsform = new mod_assign_grading_options_form(null,
1857                                                                   array('cm'=>$this->get_course_module()->id,
1858                                                                         'contextid'=>$this->context->id,
1859                                                                         'userid'=>$USER->id,
1860                                                                         'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
1861                                                                         'showquickgrading'=>$showquickgrading,
1862                                                                         'quickgrading'=>$quickgrading),
1863                                                                   'post', '',
1864                                                                   array('class'=>'gradingoptionsform'));
1866         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1867                                                                   array('cm'=>$this->get_course_module()->id,
1868                                                                         'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1869                                                                   'post', '',
1870                                                                   array('class'=>'gradingbatchoperationsform'));
1872         $gradingoptionsdata = new stdClass();
1873         $gradingoptionsdata->perpage = $perpage;
1874         $gradingoptionsdata->filter = $filter;
1875         $gradingoptionsform->set_data($gradingoptionsdata);
1877         $actionformtext = $this->output->render($gradingactions);
1878         $o .= $this->output->render(new assign_header($this->get_instance(),
1879                                                       $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign'), $actionformtext));
1880         $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);
1882         // plagiarism update status apearring in the grading book
1883         if (!empty($CFG->enableplagiarism)) {
1884             /** Include plagiarismlib.php */
1885             require_once($CFG->libdir . '/plagiarismlib.php');
1886             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
1887         }
1889         // load and print the table of submissions
1890         if ($showquickgrading && $quickgrading) {
1891             $table = $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, true));
1892             $quickgradingform = new mod_assign_quick_grading_form(null,
1893                                                                   array('cm'=>$this->get_course_module()->id,
1894                                                                         'gradingtable'=>$table));
1895             $o .= $this->output->render(new assign_form('quickgradingform', $quickgradingform));
1896         } else {
1897             $o .= $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, false));
1898         }
1900         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1901         $users = array_keys($this->list_participants($currentgroup, true));
1902         if (count($users) != 0) {
1903             // if no enrolled user in a course then don't display the batch operations feature
1904             $o .= $this->output->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
1905         }
1906         $o .= $this->output->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
1907         return $o;
1908     }
1910     /**
1911      * View entire grading page.
1912      *
1913      * @return string
1914      */
1915     private function view_grading_page() {
1916         global $CFG;
1918         $o = '';
1919         // Need submit permission to submit an assignment
1920         require_capability('mod/assign:grade', $this->context);
1921         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1923         // only load this if it is
1925         $o .= $this->view_grading_table();
1927         $o .= $this->view_footer();
1928         $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
1929         return $o;
1930     }
1932     /**
1933      * Capture the output of the plagiarism plugins disclosures and return it as a string
1934      *
1935      * @return void
1936      */
1937     private function plagiarism_print_disclosure() {
1938         global $CFG;
1939         $o = '';
1941         if (!empty($CFG->enableplagiarism)) {
1942             /** Include plagiarismlib.php */
1943             require_once($CFG->libdir . '/plagiarismlib.php');
1945             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
1946         }
1948         return $o;
1949     }
1951     /**
1952      * message for students when assignment submissions have been closed
1953      *
1954      * @return string
1955      */
1956     private function view_student_error_message() {
1957         global $CFG;
1959         $o = '';
1960         // Need submit permission to submit an assignment
1961         require_capability('mod/assign:submit', $this->context);
1963         $o .= $this->output->render(new assign_header($this->get_instance(),
1964                                                       $this->get_context(),
1965                                                       $this->show_intro(),
1966                                                       $this->get_course_module()->id,
1967                                                       get_string('editsubmission', 'assign')));
1969         $o .= $this->output->notification(get_string('submissionsclosed', 'assign'));
1971         $o .= $this->view_footer();
1973         return $o;
1975     }
1977     /**
1978      * View edit submissions page.
1979      *
1980      * @param moodleform $mform
1981      * @param array $notices A list of notices to display at the top of the edit submission form (e.g. from plugins).
1982      * @return void
1983      */
1984     private function view_edit_submission_page($mform, $notices) {
1985         global $CFG;
1987         $o = '';
1988         // Include submission form
1989         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
1990         // Need submit permission to submit an assignment
1991         require_capability('mod/assign:submit', $this->context);
1993         if (!$this->submissions_open()) {
1994             return $this->view_student_error_message();
1995         }
1996         $o .= $this->output->render(new assign_header($this->get_instance(),
1997                                                       $this->get_context(),
1998                                                       $this->show_intro(),
1999                                                       $this->get_course_module()->id,
2000                                                       get_string('editsubmission', 'assign')));
2001         $o .= $this->plagiarism_print_disclosure();
2002         $data = new stdClass();
2004         if (!$mform) {
2005             $mform = new mod_assign_submission_form(null, array($this, $data));
2006         }
2008         foreach ($notices as $notice) {
2009             $o .= $this->output->notification($notice);
2010         }
2012         $o .= $this->output->render(new assign_form('editsubmissionform',$mform));
2014         $o .= $this->view_footer();
2015         $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
2017         return $o;
2018     }
2020     /**
2021      * See if this assignment has a grade yet
2022      *
2023      * @param int $userid
2024      * @return bool
2025      */
2026     private function is_graded($userid) {
2027         $grade = $this->get_user_grade($userid, false);
2028         if ($grade) {
2029             return ($grade->grade !== NULL && $grade->grade >= 0);
2030         }
2031         return false;
2032     }
2035     /**
2036      * Perform an access check to see if the current $USER can view this users submission
2037      *
2038      * @param int $userid
2039      * @return bool
2040      */
2041     public function can_view_submission($userid) {
2042         global $USER;
2044         if (!is_enrolled($this->get_course_context(), $userid)) {
2045             return false;
2046         }
2047         if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
2048             return false;
2049         }
2050         if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
2051             return false;
2052         }
2053         return true;
2054     }
2056     /**
2057      * Ask the user to confirm they want to perform this batch operation
2058      * @return string
2059      */
2060     private function process_batch_grading_operation() {
2061         global $CFG;
2062         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2063         require_sesskey();
2065         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2066                                                                   array('cm'=>$this->get_course_module()->id,
2067                                                                         'submissiondrafts'=>$this->get_instance()->submissiondrafts),
2068                                                                   'post', '',
2069                                                                   array('class'=>'gradingbatchoperationsform'));
2071         if ($data = $gradingbatchoperationsform->get_data()) {
2072             // get the list of users
2073             $users = $data->selectedusers;
2074             $userlist = explode(',', $users);
2076             foreach ($userlist as $userid) {
2077                 if ($data->operation == 'lock') {
2078                     $this->process_lock($userid);
2079                 } else if ($data->operation == 'unlock') {
2080                     $this->process_unlock($userid);
2081                 } else if ($data->operation == 'reverttodraft') {
2082                     $this->process_revert_to_draft($userid);
2083                 }
2084             }
2085         }
2087         return true;
2088     }
2090     /**
2091      * Ask the user to confirm they want to submit their work for grading
2092      * @return string
2093      */
2094     private function check_submit_for_grading() {
2095         global $USER;
2096         // Check that all of the submission plugins are ready for this submission
2097         $notifications = array();
2098         $submission = $this->get_user_submission($USER->id, false);
2099         $plugins = $this->get_submission_plugins();
2100         foreach ($plugins as $plugin) {
2101             if ($plugin->is_enabled() && $plugin->is_visible()) {
2102                 $check = $plugin->precheck_submission($submission);
2103                 if ($check !== true) {
2104                     $notifications[] = $check;
2105                 }
2106             }
2107         }
2109         $o = '';
2110         $o .= $this->output->header();
2111         $o .= $this->output->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id));
2112         $o .= $this->view_footer();
2113         return $o;
2114     }
2116     /**
2117      * Print 2 tables of information with no action links -
2118      * the submission summary and the grading summary
2119      *
2120      * @param stdClass $user the user to print the report for
2121      * @param bool $showlinks - Return plain text or links to the profile
2122      * @return string - the html summary
2123      */
2124     public function view_student_summary($user, $showlinks) {
2125         global $CFG, $DB, $PAGE;
2127         $grade = $this->get_user_grade($user->id, false);
2128         $submission = $this->get_user_submission($user->id, false);
2129         $o = '';
2131         if ($this->can_view_submission($user->id)) {
2132             $showedit = has_capability('mod/assign:submit', $this->context) &&
2133                          $this->submissions_open() && ($this->is_any_submission_plugin_enabled()) && $showlinks;
2134             $showsubmit = $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT) && $showlinks;
2135             if (!$this->get_instance()->submissiondrafts) {
2136                 $showsubmit = false;
2137             }
2138             $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
2140             $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
2141                                                               $this->get_instance()->alwaysshowdescription,
2142                                                               $submission,
2143                                                               $this->is_any_submission_plugin_enabled(),
2144                                                               $gradelocked,
2145                                                               $this->is_graded($user->id),
2146                                                               $this->get_instance()->duedate,
2147                                                               $this->get_submission_plugins(),
2148                                                               $this->get_return_action(),
2149                                                               $this->get_return_params(),
2150                                                               $this->get_course_module()->id,
2151                                                               assign_submission_status::STUDENT_VIEW,
2152                                                               $showedit,
2153                                                               $showsubmit));
2154             require_once($CFG->libdir.'/gradelib.php');
2155             require_once($CFG->dirroot.'/grade/grading/lib.php');
2157             $gradinginfo = grade_get_grades($this->get_course()->id,
2158                                         'mod',
2159                                         'assign',
2160                                         $this->get_instance()->id,
2161                                         $user->id);
2163             $gradingitem = $gradinginfo->items[0];
2164             $gradebookgrade = $gradingitem->grades[$user->id];
2166             // check to see if all feedback plugins are empty
2167             $emptyplugins = true;
2168             if ($grade) {
2169                 foreach ($this->get_feedback_plugins() as $plugin) {
2170                     if ($plugin->is_visible() && $plugin->is_enabled()) {
2171                         if (!$plugin->is_empty($grade)) {
2172                             $emptyplugins = false;
2173                         }
2174                     }
2175                 }
2176             }
2179             if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
2181                 $gradefordisplay = '';
2182                 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2184                 if ($controller = $gradingmanager->get_active_controller()) {
2185                     $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
2186                     $gradefordisplay = $controller->render_grade($PAGE,
2187                                                                  $grade->id,
2188                                                                  $gradingitem,
2189                                                                  $gradebookgrade->str_long_grade,
2190                                                                  has_capability('mod/assign:grade', $this->get_context()));
2191                 } else {
2192                     $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
2193                 }
2195                 $gradeddate = $gradebookgrade->dategraded;
2196                 $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));
2198                 $feedbackstatus = new assign_feedback_status($gradefordisplay,
2199                                                       $gradeddate,
2200                                                       $grader,
2201                                                       $this->get_feedback_plugins(),
2202                                                       $grade,
2203                                                       $this->get_course_module()->id,
2204                                                       $this->get_return_action(),
2205                                                       $this->get_return_params());
2207                 $o .= $this->output->render($feedbackstatus);
2208             }
2210         }
2211         return $o;
2212     }
2214     /**
2215      * View submissions page (contains details of current submission).
2216      *
2217      * @return string
2218      */
2219     private function view_submission_page() {
2220         global $CFG, $DB, $USER, $PAGE;
2222         $o = '';
2223         $o .= $this->output->render(new assign_header($this->get_instance(),
2224                                                       $this->get_context(),
2225                                                       $this->show_intro(),
2226                                                       $this->get_course_module()->id));
2228         if ($this->can_grade()) {
2229             $o .= $this->output->render(new assign_grading_summary($this->count_participants(0),
2230                                                             $this->get_instance()->submissiondrafts,
2231                                                             $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2232                                                             $this->is_any_submission_plugin_enabled(),
2233                                                             $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2234                                                             $this->get_instance()->duedate,
2235                                                             $this->get_course_module()->id,
2236                                                             $this->count_submissions_need_grading()
2237                                                             ));
2238         }
2239         $grade = $this->get_user_grade($USER->id, false);
2240         $submission = $this->get_user_submission($USER->id, false);
2242         if ($this->can_view_submission($USER->id)) {
2243             $o .= $this->view_student_summary($USER, true);
2244         }
2247         $o .= $this->view_footer();
2248         $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
2249         return $o;
2250     }
2252     /**
2253      * convert the final raw grade(s) in the  grading table for the gradebook
2254      *
2255      * @param stdClass $grade
2256      * @return array
2257      */
2258     private function convert_grade_for_gradebook(stdClass $grade) {
2259         $gradebookgrade = array();
2260         // trying to match those array keys in grade update function in gradelib.php
2261         // with keys in th database table assign_grades
2262         // starting around line 262
2263         if ($grade->grade >= 0) {
2264             $gradebookgrade['rawgrade'] = $grade->grade;
2265         }
2266         $gradebookgrade['userid'] = $grade->userid;
2267         $gradebookgrade['usermodified'] = $grade->grader;
2268         $gradebookgrade['datesubmitted'] = NULL;
2269         $gradebookgrade['dategraded'] = $grade->timemodified;
2270         if (isset($grade->feedbackformat)) {
2271             $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
2272         }
2273         if (isset($grade->feedbacktext)) {
2274             $gradebookgrade['feedback'] = $grade->feedbacktext;
2275         }
2277         return $gradebookgrade;
2278     }
2280     /**
2281      * convert submission details for the gradebook
2282      *
2283      * @param stdClass $submission
2284      * @return array
2285      */
2286     private function convert_submission_for_gradebook(stdClass $submission) {
2287         $gradebookgrade = array();
2290         $gradebookgrade['userid'] = $submission->userid;
2291         $gradebookgrade['usermodified'] = $submission->userid;
2292         $gradebookgrade['datesubmitted'] = $submission->timemodified;
2294         return $gradebookgrade;
2295     }
2297     /**
2298      * update grades in the gradebook
2299      *
2300      * @param mixed $submission stdClass|null
2301      * @param mixed $grade stdClass|null
2302      * @return bool
2303      */
2304     private function gradebook_item_update($submission=NULL, $grade=NULL) {
2306         if($submission != NULL){
2307             $gradebookgrade = $this->convert_submission_for_gradebook($submission);
2308         }else{
2309             $gradebookgrade = $this->convert_grade_for_gradebook($grade);
2310         }
2311         // Grading is disabled, return.
2312         if ($this->grading_disabled($gradebookgrade['userid'])) {
2313             return false;
2314         }
2315         $assign = clone $this->get_instance();
2316         $assign->cmidnumber = $this->get_course_module()->id;
2318         return assign_grade_item_update($assign, $gradebookgrade);
2319     }
2321     /**
2322      * update grades in the gradebook based on submission time
2323      *
2324      * @param stdClass $submission
2325      * @param bool $updatetime
2326      * @return bool
2327      */
2328     private function update_submission(stdClass $submission, $updatetime=true) {
2329         global $DB;
2331         if ($updatetime) {
2332             $submission->timemodified = time();
2333         }
2334         $result= $DB->update_record('assign_submission', $submission);
2335         if ($result) {
2336             $this->gradebook_item_update($submission);
2337         }
2338         return $result;
2339     }
2341     /**
2342      * Is this assignment open for submissions?
2343      *
2344      * Check the due date,
2345      * prevent late submissions,
2346      * has this person already submitted,
2347      * is the assignment locked?
2348      *
2349      * @return bool
2350      */
2351     private function submissions_open() {
2352         global $USER;
2354         $time = time();
2355         $dateopen = true;
2356         if ($this->get_instance()->preventlatesubmissions && $this->get_instance()->duedate) {
2357             $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $this->get_instance()->duedate);
2358         } else {
2359             $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
2360         }
2362         if (!$dateopen) {
2363             return false;
2364         }
2366         // now check if this user has already submitted etc.
2367         if (!is_enrolled($this->get_course_context(), $USER)) {
2368             return false;
2369         }
2370         if ($submission = $this->get_user_submission($USER->id, false)) {
2371             if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2372                 // drafts are tracked and the student has submitted the assignment
2373                 return false;
2374             }
2375         }
2376         if ($grade = $this->get_user_grade($USER->id, false)) {
2377             if ($grade->locked) {
2378                 return false;
2379             }
2380         }
2382         if ($this->grading_disabled($USER->id)) {
2383             return false;
2384         }
2386         return true;
2387     }
2389     /**
2390      * render the files in file area
2391      * @param string $component
2392      * @param string $area
2393      * @param int $submissionid
2394      * @return string
2395      */
2396     public function render_area_files($component, $area, $submissionid) {
2397         global $USER;
2399         if (!$submissionid) {
2400             $submission = $this->get_user_submission($USER->id,false);
2401             $submissionid = $submission->id;
2402         }
2404         $fs = get_file_storage();
2405         $browser = get_file_browser();
2406         $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
2407         return $this->output->assign_files($this->context, $submissionid, $area, $component);
2409     }
2411     /**
2412      * Returns a list of teachers that should be grading given submission
2413      *
2414      * @param int $userid
2415      * @return array
2416      */
2417     private function get_graders($userid) {
2418         //potential graders
2419         $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");
2421         $graders = array();
2422         if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) {   // Separate groups are being used
2423             if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) {  // Try to find all groups
2424                 foreach ($groups as $group) {
2425                     foreach ($potentialgraders as $grader) {
2426                         if ($grader->id == $userid) {
2427                             continue; // do not send self
2428                         }
2429                         if (groups_is_member($group->id, $grader->id)) {
2430                             $graders[$grader->id] = $grader;
2431                         }
2432                     }
2433                 }
2434             } else {
2435                 // user not in group, try to find graders without group
2436                 foreach ($potentialgraders as $grader) {
2437                     if ($grader->id == $userid) {
2438                         continue; // do not send self
2439                     }
2440                     if (!groups_has_membership($this->get_course_module(), $grader->id)) {
2441                         $graders[$grader->id] = $grader;
2442                     }
2443                 }
2444             }
2445         } else {
2446             foreach ($potentialgraders as $grader) {
2447                 if ($grader->id == $userid) {
2448                     continue; // do not send self
2449                 }
2450                 // must be enrolled
2451                 if (is_enrolled($this->get_course_context(), $grader->id)) {
2452                     $graders[$grader->id] = $grader;
2453                 }
2454             }
2455         }
2456         return $graders;
2457     }
2459     /**
2460      * Format a notification for plain text
2461      *
2462      * @param string $messagetype
2463      * @param stdClass $info
2464      * @param stdClass $course
2465      * @param stdClass $context
2466      * @param string $modulename
2467      * @param string $assignmentname
2468      */
2469     private static function format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname) {
2470         $posttext  = format_string($course->shortname, true, array('context' => $context->get_course_context())).' -> '.
2471                      $modulename.' -> '.
2472                      format_string($assignmentname, true, array('context' => $context))."\n";
2473         $posttext .= '---------------------------------------------------------------------'."\n";
2474         $posttext .= get_string($messagetype . 'text', "assign", $info)."\n";
2475         $posttext .= "\n---------------------------------------------------------------------\n";
2476         return $posttext;
2477     }
2479     /**
2480      * Format a notification for HTML
2481      *
2482      * @param string $messagetype
2483      * @param stdClass $info
2484      * @param stdClass $course
2485      * @param stdClass $context
2486      * @param string $modulename
2487      * @param stdClass $coursemodule
2488      * @param string $assignmentname
2489      * @param stdClass $info
2490      */
2491     private static function format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) {
2492         global $CFG;
2493         $posthtml  = '<p><font face="sans-serif">'.
2494                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.format_string($course->shortname, true, array('context' => $context->get_course_context())).'</a> ->'.
2495                      '<a href="'.$CFG->wwwroot.'/mod/assign/index.php?id='.$course->id.'">'.$modulename.'</a> ->'.
2496                      '<a href="'.$CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id.'">'.format_string($assignmentname, true, array('context' => $context)).'</a></font></p>';
2497         $posthtml .= '<hr /><font face="sans-serif">';
2498         $posthtml .= '<p>'.get_string($messagetype . 'html', 'assign', $info).'</p>';
2499         $posthtml .= '</font><hr />';
2500         return $posthtml;
2501     }
2503     /**
2504      * Message someone about something (static so it can be called from cron)
2505      *
2506      * @param stdClass $userfrom
2507      * @param stdClass $userto
2508      * @param string $messagetype
2509      * @param string $eventtype
2510      * @param int $updatetime
2511      * @param stdClass $coursemodule
2512      * @param stdClass $context
2513      * @param stdClass $course
2514      * @param string $modulename
2515      * @param string $assignmentname
2516      * @return void
2517      */
2518     public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
2519                                                         $updatetime, $coursemodule, $context, $course,
2520                                                         $modulename, $assignmentname) {
2521         global $CFG;
2523         $info = new stdClass();
2524         $info->username = fullname($userfrom, true);
2525         $info->assignment = format_string($assignmentname,true, array('context'=>$context));
2526         $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
2527         $info->timeupdated = userdate($updatetime, get_string('strftimerecentfull'));
2529         $postsubject = get_string($messagetype . 'small', 'assign', $info);
2530         $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
2531         $posthtml = ($userto->mailformat == 1) ? self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) : '';
2533         $eventdata = new stdClass();
2534         $eventdata->modulename       = 'assign';
2535         $eventdata->userfrom         = $userfrom;
2536         $eventdata->userto           = $userto;
2537         $eventdata->subject          = $postsubject;
2538         $eventdata->fullmessage      = $posttext;
2539         $eventdata->fullmessageformat = FORMAT_PLAIN;
2540         $eventdata->fullmessagehtml  = $posthtml;
2541         $eventdata->smallmessage     = $postsubject;
2543         $eventdata->name            = $eventtype;
2544         $eventdata->component       = 'mod_assign';
2545         $eventdata->notification    = 1;
2546         $eventdata->contexturl      = $info->url;
2547         $eventdata->contexturlname  = $info->assignment;
2549         message_send($eventdata);
2550     }
2552     /**
2553      * Message someone about something
2554      *
2555      * @param stdClass $userfrom
2556      * @param stdClass $userto
2557      * @param string $messagetype
2558      * @param string $eventtype
2559      * @param int $updatetime
2560      * @return void
2561      */
2562     public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
2563         self::send_assignment_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime, $this->get_course_module(), $this->get_context(), $this->get_course(), $this->get_module_name(), $this->get_instance()->name);
2564     }
2566     /**
2567      * Notify student upon successful submission
2568      *
2569      * @global moodle_database $DB
2570      * @param stdClass $submission
2571      * @return void
2572      */
2573     private function notify_student_submission_receipt(stdClass $submission) {
2574         global $DB;
2576         $adminconfig = $this->get_admin_config();
2577         if (!$adminconfig->submissionreceipts) {
2578             // No need to do anything
2579             return;
2580         }
2581         $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
2582         $this->send_notification($user, $user, 'submissionreceipt', 'assign_notification', $submission->timemodified);
2583     }
2585     /**
2586      * Send notifications to graders upon student submissions
2587      *
2588      * @global moodle_database $DB
2589      * @param stdClass $submission
2590      * @return void
2591      */
2592     private function notify_graders(stdClass $submission) {
2593         global $DB;
2595         $late = $this->get_instance()->duedate && ($this->get_instance()->duedate < time());
2597         if (!$this->get_instance()->sendnotifications && !($late && $this->get_instance()->sendlatenotifications)) {          // No need to do anything
2598             return;
2599         }
2601         $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
2602         if ($teachers = $this->get_graders($user->id)) {
2603             foreach ($teachers as $teacher) {
2604                 $this->send_notification($user, $teacher, 'gradersubmissionupdated', 'assign_notification', $submission->timemodified);
2605             }
2606         }
2607     }
2609     /**
2610      * assignment submission is processed before grading
2611      *
2612      * @return void
2613      */
2614     private function process_submit_for_grading() {
2615         global $USER;
2617         // Need submit permission to submit an assignment
2618         require_capability('mod/assign:submit', $this->context);
2619         require_sesskey();
2621         $submission = $this->get_user_submission($USER->id,true);
2622         if ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2623             // Give each submission plugin a chance to process the submission
2624             $plugins = $this->get_submission_plugins();
2625             foreach ($plugins as $plugin) {
2626                 $plugin->submit_for_grading();
2627             }
2629             $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2630             $this->update_submission($submission);
2631             $this->add_to_log('submit for grading', $this->format_submission_for_log($submission));
2632             $this->notify_graders($submission);
2633             $this->notify_student_submission_receipt($submission);
2634         }
2635     }
2637     /**
2638      * save quick grades
2639      *
2640      * @global moodle_database $DB
2641      * @return string The result of the save operation
2642      */
2643     private function process_save_quick_grades() {
2644         global $USER, $DB, $CFG;
2646         // Need grade permission
2647         require_capability('mod/assign:grade', $this->context);
2649         // make sure advanced grading is disabled
2650         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2651         $controller = $gradingmanager->get_active_controller();
2652         if (!empty($controller)) {
2653             return get_string('errorquickgradingvsadvancedgrading', 'assign');
2654         }
2656         $users = array();
2657         // first check all the last modified values
2658         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2659         $participants = $this->list_participants($currentgroup, true);
2661         // gets a list of possible users and look for values based upon that.
2662         foreach ($participants as $userid => $unused) {
2663             $modified = optional_param('grademodified_' . $userid, -1, PARAM_INT);
2664             // Gather the userid, updated grade and last modified value.
2665             $record = new stdClass();
2666             $record->userid = $userid;
2667             $gradevalue = optional_param('quickgrade_' . $userid, '', PARAM_TEXT);
2668             if($modified >= 0) {
2669                 $record->grade = unformat_float(optional_param('quickgrade_' . $record->userid, -1, PARAM_TEXT));
2670             }
2671             $record->lastmodified = $modified;
2672             $record->gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2673             $users[$userid] = $record;
2674         }
2676         list($userids, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED);
2677         $params['assignment'] = $this->get_instance()->id;
2678         // check them all for currency
2679         $sql = 'SELECT u.id as userid, g.grade as grade, g.timemodified as lastmodified
2680                   FROM {user} u
2681              LEFT JOIN {assign_grades} g ON u.id = g.userid AND g.assignment = :assignment
2682                  WHERE u.id ' . $userids;
2683         $currentgrades = $DB->get_recordset_sql($sql, $params);
2685         $modifiedusers = array();
2686         foreach ($currentgrades as $current) {
2687             $modified = $users[(int)$current->userid];
2688             $grade = $this->get_user_grade($modified->userid, false);
2690             // check to see if the outcomes were modified
2691             if ($CFG->enableoutcomes) {
2692                 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2693                     $oldoutcome = $outcome->grades[$modified->userid]->grade;
2694                     $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_FLOAT);
2695                     if ($oldoutcome != $newoutcome) {
2696                         // can't check modified time for outcomes because it is not reported
2697                         $modifiedusers[$modified->userid] = $modified;
2698                         continue;
2699                     }
2700                 }
2701             }
2703             // let plugins participate
2704             foreach ($this->feedbackplugins as $plugin) {
2705                 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2706                     if ($plugin->is_quickgrading_modified($modified->userid, $grade)) {
2707                         if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2708                             return get_string('errorrecordmodified', 'assign');
2709                         } else {
2710                             $modifiedusers[$modified->userid] = $modified;
2711                             continue;
2712                         }
2713                     }
2714                 }
2715             }
2718             if (($current->grade < 0 || $current->grade === NULL) &&
2719                 ($modified->grade < 0 || $modified->grade === NULL)) {
2720                 // different ways to indicate no grade
2721                 continue;
2722             }
2723             // Treat 0 and null as different values
2724             if ($current->grade !== null) {
2725                 $current->grade = floatval($current->grade);
2726             }
2727             if ($current->grade !== $modified->grade) {
2728                 // grade changed
2729                 if ($this->grading_disabled($modified->userid)) {
2730                     continue;
2731                 }
2732                 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2733                     // error - record has been modified since viewing the page
2734                     return get_string('errorrecordmodified', 'assign');
2735                 } else {
2736                     $modifiedusers[$modified->userid] = $modified;
2737                 }
2738             }
2740         }
2741         $currentgrades->close();
2743         $adminconfig = $this->get_admin_config();
2744         $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
2746         // ok - ready to process the updates
2747         foreach ($modifiedusers as $userid => $modified) {
2748             $grade = $this->get_user_grade($userid, true);
2749             $grade->grade= grade_floatval(unformat_float($modified->grade));
2750             $grade->grader= $USER->id;
2752             // save plugins data
2753             foreach ($this->feedbackplugins as $plugin) {
2754                 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2755                     $plugin->save_quickgrading_changes($userid, $grade);
2756                     if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
2757                         // This is the feedback plugin chose to push comments to the gradebook.
2758                         $grade->feedbacktext = $plugin->text_for_gradebook($grade);
2759                         $grade->feedbackformat = $plugin->format_for_gradebook($grade);
2760                     }
2761                 }
2762             }
2764             $this->update_grade($grade);
2766             // save outcomes
2767             if ($CFG->enableoutcomes) {
2768                 $data = array();
2769                 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2770                     $oldoutcome = $outcome->grades[$modified->userid]->grade;
2771                     $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_INT);
2772                     if ($oldoutcome != $newoutcome) {
2773                         $data[$outcomeid] = $newoutcome;
2774                     }
2775                 }
2776                 if (count($data) > 0) {
2777                     grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
2778                 }
2779             }
2781             $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
2782         }
2784         return get_string('quickgradingchangessaved', 'assign');
2785     }
2787     /**
2788      * save grading options
2789      *
2790      * @return void
2791      */
2792     private function process_save_grading_options() {
2793         global $USER, $CFG;
2795         // Include grading options form
2796         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2798         // Need submit permission to submit an assignment
2799         require_capability('mod/assign:grade', $this->context);
2801         $mform = new mod_assign_grading_options_form(null, array('cm'=>$this->get_course_module()->id,
2802                                                                  'contextid'=>$this->context->id,
2803                                                                  'userid'=>$USER->id,
2804                                                                  'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2805                                                                  'showquickgrading'=>false));
2806         if ($formdata = $mform->get_data()) {
2807             set_user_preference('assign_perpage', $formdata->perpage);
2808             if (isset($formdata->filter)) {
2809                 set_user_preference('assign_filter', $formdata->filter);
2810             }
2811         }
2812     }
2814    /**
2815     * Take a grade object and print a short summary for the log file.
2816     * The size limit for the log file is 255 characters, so be careful not
2817     * to include too much information.
2818     *
2819     * @param stdClass $grade
2820     * @return string
2821     */
2822     private function format_grade_for_log(stdClass $grade) {
2823         global $DB;
2825         $user = $DB->get_record('user', array('id' => $grade->userid), '*', MUST_EXIST);
2827         $info = get_string('gradestudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
2828         if ($grade->grade != '') {
2829             $info .= get_string('grade') . ': ' . $this->display_grade($grade->grade, false) . '. ';
2830         } else {
2831             $info .= get_string('nograde', 'assign');
2832         }
2833         if ($grade->locked) {
2834             $info .= get_string('submissionslocked', 'assign') . '. ';
2835         }
2836         return $info;
2837     }
2839     /**
2840      * Take a submission object and print a short summary for the log file.
2841      * The size limit for the log file is 255 characters, so be careful not
2842      * to include too much information.
2843      *
2844      * @param stdClass $submission
2845      * @return string
2846      */
2847     private function format_submission_for_log(stdClass $submission) {
2848         $info = '';
2849         $info .= get_string('submissionstatus', 'assign') . ': ' . get_string('submissionstatus_' . $submission->status, 'assign') . '. <br>';
2850         // format_for_log here iterating every single log INFO  from either submission or grade in every assignment plugin
2852         foreach ($this->submissionplugins as $plugin) {
2853             if ($plugin->is_enabled() && $plugin->is_visible()) {
2856                 $info .= "<br>" . $plugin->format_for_log($submission);
2857             }
2858         }
2861         return $info;
2862     }
2864     /**
2865      * save assignment submission
2866      *
2867      * @param  moodleform $mform
2868      * @param  array $notices Any error messages that should be shown to the user at the top of the edit submission form.
2869      * @return bool
2870      */
2871     private function process_save_submission(&$mform, &$notices) {
2872         global $USER, $CFG;
2874         // Include submission form.
2875         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2877         // Need submit permission to submit an assignment.
2878         require_capability('mod/assign:submit', $this->context);
2879         require_sesskey();
2881         $data = new stdClass();
2882         $mform = new mod_assign_submission_form(null, array($this, $data));
2883         if ($mform->is_cancelled()) {
2884             return true;
2885         }
2886         if ($data = $mform->get_data()) {
2887             $submission = $this->get_user_submission($USER->id, true); //create the submission if needed & its id
2888             if ($this->get_instance()->submissiondrafts) {
2889                 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2890             } else {
2891                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2892             }
2894             $grade = $this->get_user_grade($USER->id, false); // get the grade to check if it is locked
2895             if ($grade && $grade->locked) {
2896                 print_error('submissionslocked', 'assign');
2897                 return true;
2898             }
2900             $allempty = true;
2901             $pluginerror = false;
2902             foreach ($this->submissionplugins as $plugin) {
2903                 if ($plugin->is_enabled()) {
2904                     if (!$plugin->save($submission, $data)) {
2905                         $notices[] = $plugin->get_error();
2906                         $pluginerror = true;
2907                     }
2908                     if (!$allempty || !$plugin->is_empty($submission)) {
2909                         $allempty = false;
2910                     }
2911                 }
2912             }
2913             if ($pluginerror || $allempty) {
2914                 if ($allempty) {
2915                     $notices[] = get_string('submissionempty', 'mod_assign');
2916                 }
2917                 return false;
2918             }
2920             $this->update_submission($submission);
2922             // Logging
2923             $this->add_to_log('submit', $this->format_submission_for_log($submission));
2925             if (!$this->get_instance()->submissiondrafts) {
2926                 $this->notify_student_submission_receipt($submission);
2927                 $this->notify_graders($submission);
2928             }
2929             return true;
2930         }
2931         return false;
2932     }
2935     /**
2936      * Determine if this users grade is locked or overridden
2937      *
2938      * @param int $userid - The student userid
2939      * @return bool $gradingdisabled
2940      */
2941     public function grading_disabled($userid) {
2942         global $CFG;
2944         $gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2945         if (!$gradinginfo) {
2946             return false;
2947         }
2949         if (!isset($gradinginfo->items[0]->grades[$userid])) {
2950             return false;
2951         }
2952         $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
2953         return $gradingdisabled;
2954     }
2957     /**
2958      * Get an instance of a grading form if advanced grading is enabled
2959      * This is specific to the assignment, marker and student
2960      *
2961      * @param int $userid - The student userid
2962      * @param bool $gradingdisabled
2963      * @return mixed gradingform_instance|null $gradinginstance
2964      */
2965     private function get_grading_instance($userid, $gradingdisabled) {
2966         global $CFG, $USER;
2968         $grade = $this->get_user_grade($userid, false);
2969         $grademenu = make_grades_menu($this->get_instance()->grade);
2971         $advancedgradingwarning = false;
2972         $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2973         $gradinginstance = null;
2974         if ($gradingmethod = $gradingmanager->get_active_method()) {
2975             $controller = $gradingmanager->get_controller($gradingmethod);
2976             if ($controller->is_form_available()) {
2977                 $itemid = null;
2978                 if ($grade) {
2979                     $itemid = $grade->id;
2980                 }
2981                 if ($gradingdisabled && $itemid) {
2982                     $gradinginstance = ($controller->get_current_instance($USER->id, $itemid));
2983                 } else if (!$gradingdisabled) {
2984                     $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
2985                     $gradinginstance = ($controller->get_or_create_instance($instanceid, $USER->id, $itemid));
2986                 }
2987             } else {
2988                 $advancedgradingwarning = $controller->form_unavailable_notification();
2989             }
2990         }
2991         if ($gradinginstance) {
2992             $gradinginstance->get_controller()->set_grade_range($grademenu);
2993         }
2994         return $gradinginstance;
2995     }
2997     /**
2998      * add elements to grade form
2999      *
3000      * @param MoodleQuickForm $mform
3001      * @param stdClass $data
3002      * @param array $params
3003      * @return void
3004      */
3005     public function add_grade_form_elements(MoodleQuickForm $mform, stdClass $data, $params) {
3006         global $USER, $CFG;
3007         $settings = $this->get_instance();
3009         $rownum = $params['rownum'];
3010         $last = $params['last'];
3011         $useridlist = $params['useridlist'];
3012         $userid = $useridlist[$rownum];
3013         $grade = $this->get_user_grade($userid, false);
3015         // add advanced grading
3016         $gradingdisabled = $this->grading_disabled($userid);
3017         $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
3019         if ($gradinginstance) {
3020             $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
3021             if ($gradingdisabled) {
3022                 $gradingelement->freeze();
3023             } else {
3024                 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
3025             }
3026         } else {
3027             // use simple direct grading
3028             if ($this->get_instance()->grade > 0) {
3029                 $gradingelement = $mform->addElement('text', 'grade', get_string('gradeoutof', 'assign',$this->get_instance()->grade));
3030                 $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
3031                 $mform->setType('grade', PARAM_TEXT);
3032                 if ($gradingdisabled) {
3033                     $gradingelement->freeze();
3034                 }
3035             } else {
3036                 $grademenu = make_grades_menu($this->get_instance()->grade);
3037                 if (count($grademenu) > 0) {
3038                     $gradingelement = $mform->addElement('select', 'grade', get_string('grade').':', $grademenu);
3040                     // The grade is already formatted with format_float so it needs to be converted back to an integer.
3041                     if (!empty($data->grade)) {
3042                         $data->grade = (int)unformat_float($data->grade);
3043                     }
3044                     $mform->setType('grade', PARAM_INT);
3045                     if ($gradingdisabled) {
3046                         $gradingelement->freeze();
3047                     }
3048                 }
3049             }
3050         }
3052         $gradinginfo = grade_get_grades($this->get_course()->id,
3053                                         'mod',
3054                                         'assign',
3055                                         $this->get_instance()->id,
3056                                         $userid);
3057         if (!empty($CFG->enableoutcomes)) {
3058             foreach($gradinginfo->outcomes as $index=>$outcome) {
3059                 $options = make_grades_menu(-$outcome->scaleid);
3060                 if ($outcome->grades[$userid]->locked) {
3061                     $options[0] = get_string('nooutcome', 'grades');
3062                     $mform->addElement('static', 'outcome_'.$index.'['.$userid.']', $outcome->name.':',
3063                             $options[$outcome->grades[$userid]->grade]);
3064                 } else {
3065                     $options[''] = get_string('nooutcome', 'grades');
3066                     $attributes = array('id' => 'menuoutcome_'.$index );
3067                     $mform->addElement('select', 'outcome_'.$index.'['.$userid.']', $outcome->name.':', $options, $attributes );
3068                     $mform->setType('outcome_'.$index.'['.$userid.']', PARAM_INT);
3069                     $mform->setDefault('outcome_'.$index.'['.$userid.']', $outcome->grades[$userid]->grade );
3070                 }
3071             }
3072         }
3074         if (has_all_capabilities(array('gradereport/grader:view', 'moodle/grade:viewall'), $this->get_course_context())) {
3075             $gradestring = $this->output->action_link(new moodle_url('/grade/report/grader/index.php',
3076                                                               array('id'=>$this->get_course()->id)),
3077                                                 $gradinginfo->items[0]->grades[$userid]->str_grade);
3078         } else {
3079             $gradestring = $gradinginfo->items[0]->grades[$userid]->str_grade;
3080         }
3081         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assign').':', $gradestring);
3084         $mform->addElement('static', 'progress', '', get_string('gradingstudentprogress', 'assign', array('index'=>$rownum+1, 'count'=>count($useridlist))));
3086         // Let feedback plugins add elements to the grading form.
3087         $this->add_plugin_grade_elements($grade, $mform, $data, $userid);
3089         // hidden params
3090         $mform->addElement('hidden', 'id', $this->get_course_module()->id);
3091         $mform->setType('id', PARAM_INT);
3092         $mform->addElement('hidden', 'rownum', $rownum);
3093         $mform->setType('rownum', PARAM_INT);
3094         $mform->setConstant('rownum', $rownum);
3095         $mform->addElement('hidden', 'useridlist', implode(',', $useridlist));
3096         $mform->setType('useridlist', PARAM_TEXT);
3097         $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT));
3098         $mform->setType('ajax', PARAM_INT);
3100         $mform->addElement('hidden', 'action', 'submitgrade');
3101         $mform->setType('action', PARAM_ALPHA);
3104         $buttonarray=array();
3105         $buttonarray[] = $mform->createElement('submit', 'savegrade', get_string('savechanges', 'assign'));
3106         if (!$last){
3107             $buttonarray[] = $mform->createElement('submit', 'saveandshownext', get_string('savenext','assign'));
3108         }
3109         $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
3110         $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
3111         $mform->closeHeaderBefore('buttonar');
3112         $buttonarray=array();
3114         if ($rownum > 0) {
3115             $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', get_string('previous','assign'));
3116         }
3118         if (!$last){
3119             $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', get_string('nosavebutnext', 'assign'));
3120         }
3121         if (!empty($buttonarray)) {
3122             $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
3123         }
3124     }
3127     /**
3128      * add elements in submission plugin form
3129      *
3130      * @param mixed $submission stdClass|null
3131      * @param MoodleQuickForm $mform
3132      * @param stdClass $data
3133      * @param int $userid The current userid (same as $USER->id)
3134      * @return void
3135      */
3136     private function add_plugin_submission_elements($submission, MoodleQuickForm $mform, stdClass $data, $userid) {
3137         foreach ($this->submissionplugins as $plugin) {
3138             if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
3139                 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
3140                 if (!$plugin->get_form_elements_for_user($submission, $mform, $data, $userid)) {
3141                     $mform->removeElement('header_' . $plugin->get_type());
3142                 }
3143             }
3144         }
3145     }
3147     /**
3148      * check if feedback plugins installed are enabled
3149      *
3150      * @return bool
3151      */
3152     public function is_any_feedback_plugin_enabled() {
3153         if (!isset($this->cache['any_feedback_plugin_enabled'])) {
3154             $this->cache['any_feedback_plugin_enabled'] = false;
3155             foreach ($this->feedbackplugins as $plugin) {
3156                 if ($plugin->is_enabled() && $plugin->is_visible()) {
3157                     $this->cache['any_feedback_plugin_enabled'] = true;
3158                     break;
3159                 }
3160             }
3161         }
3163         return $this->cache['any_feedback_plugin_enabled'];
3165     }
3167     /**
3168      * check if submission plugins installed are enabled
3169      *
3170      * @return bool
3171      */
3172     public function is_any_submission_plugin_enabled() {
3173         if (!isset($this->cache['any_submission_plugin_enabled'])) {
3174             $this->cache['any_submission_plugin_enabled'] = false;
3175             foreach ($this->submissionplugins as $plugin) {
3176                 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
3177                     $this->cache['any_submission_plugin_enabled'] = true;
3178                     break;
3179                 }
3180             }
3181         }
3183         return $this->cache['any_submission_plugin_enabled'];
3185     }
3187     /**
3188      * add elements to submission form
3189      * @param MoodleQuickForm $mform
3190      * @param stdClass $data
3191      * @return void
3192      */
3193     public function add_submission_form_elements(MoodleQuickForm $mform, stdClass $data) {
3194         global $USER;
3196         // online text submissions
3198         $submission = $this->get_user_submission($USER->id, false);
3200         $this->add_plugin_submission_elements($submission, $mform, $data, $USER->id);
3202         // hidden params
3203         $mform->addElement('hidden', 'id', $this->get_course_module()->id);
3204         $mform->setType('id', PARAM_INT);
3206         $mform->addElement('hidden', 'action', 'savesubmission');
3207         $mform->setType('action', PARAM_TEXT);
3208         // buttons
3210     }
3212     /**
3213      * revert to draft
3214      * Uses url parameter userid
3215      *
3216      * @param int $userid
3217      * @return void
3218      */
3219     private function process_revert_to_draft($userid = 0) {
3220         global $USER, $DB;
3222         // Need grade permission
3223         require_capability('mod/assign:grade', $this->context);
3224         require_sesskey();
3226         if (!$userid) {
3227             $userid = required_param('userid', PARAM_INT);
3228         }
3230         $submission = $this->get_user_submission($userid, false);
3231         if (!$submission) {
3232             return;
3233         }
3234         $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3235         $this->update_submission($submission, false);
3237         // update the modified time on the grade (grader modified)
3238         $grade = $this->get_user_grade($userid, true);
3239         $this->update_grade($grade);
3241         $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3243         $this->add_to_log('revert submission to draft', get_string('reverttodraftforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3245     }
3247     /**
3248      * lock  the process
3249      * Uses url parameter userid
3250      * @param int $userid
3251      * @return void
3252      */
3253     private function process_lock($userid = 0) {
3254         global $USER, $DB;
3256         // Need grade permission
3257         require_capability('mod/assign:grade', $this->context);
3258         require_sesskey();
3260         if (!$userid) {
3261             $userid = required_param('userid', PARAM_INT);
3262         }
3264         $grade = $this->get_user_grade($userid, true);
3265         $grade->locked = 1;
3266         $grade->grader = $USER->id;
3267         $this->update_grade($grade);
3269         $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3271         $this->add_to_log('lock submission', get_string('locksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3272     }
3274     /**
3275      * unlock the process
3276      *
3277      * @param int $userid
3278      * @return void
3279      */
3280     private function process_unlock($userid = 0) {
3281         global $USER, $DB;
3283         // Need grade permission
3284         require_capability('mod/assign:grade', $this->context);
3285         require_sesskey();
3287         if (!$userid) {
3288             $userid = required_param('userid', PARAM_INT);
3289         }
3291         $grade = $this->get_user_grade($userid, true);
3292         $grade->locked = 0;
3293         $grade->grader = $USER->id;
3294         $this->update_grade($grade);
3296         $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3298         $this->add_to_log('unlock submission', get_string('unlocksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3299     }
3301     /**
3302      * save outcomes submitted from grading form
3303      *
3304      * @param int $userid
3305      * @param stdClass $formdata
3306      */
3307     private function process_outcomes($userid, $formdata) {
3308         global $CFG, $USER;
3310         if (empty($CFG->enableoutcomes)) {
3311             return;
3312         }
3313         if ($this->grading_disabled($userid)) {
3314             return;
3315         }
3317         require_once($CFG->libdir.'/gradelib.php');
3319         $data = array();
3320         $gradinginfo = grade_get_grades($this->get_course()->id,
3321                                         'mod',
3322                                         'assign',
3323                                         $this->get_instance()->id,
3324                                         $userid);
3326         if (!empty($gradinginfo->outcomes)) {
3327             foreach($gradinginfo->outcomes as $index=>$oldoutcome) {
3328                 $name = 'outcome_'.$index;
3329     &