MDL-36289: Assignment - Prevent feedback files being copied to the next user when...
[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;
300         // handle form submissions first
301         if ($action == 'savesubmission') {
302             $action = 'editsubmission';
303             if ($this->process_save_submission($mform)) {
304                 $action = 'view';
305             }
306          } else if ($action == 'lock') {
307             $this->process_lock();
308             $action = 'grading';
309          } else if ($action == 'reverttodraft') {
310             $this->process_revert_to_draft();
311             $action = 'grading';
312          } else if ($action == 'unlock') {
313             $this->process_unlock();
314             $action = 'grading';
315          } else if ($action == 'confirmsubmit') {
316             $this->process_submit_for_grading();
317             // save and show next button
318          } else if ($action == 'batchgradingoperation') {
319             $this->process_batch_grading_operation();
320             $action = 'grading';
321          } else if ($action == 'submitgrade') {
322             if (optional_param('saveandshownext', null, PARAM_RAW)) {
323                 //save and show next
324                 $action = 'grade';
325                 if ($this->process_save_grade($mform)) {
326                     $action = 'nextgrade';
327                 }
328             } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
329                 $action = 'previousgrade';
330             } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
331                 //show next button
332                 $action = 'nextgrade';
333             } else if (optional_param('savegrade', null, PARAM_RAW)) {
334                 //save changes button
335                 $action = 'grade';
336                 if ($this->process_save_grade($mform)) {
337                     $action = 'grading';
338                 }
339             } else {
340                 //cancel button
341                 $action = 'grading';
342             }
343         }else if ($action == 'quickgrade') {
344             $message = $this->process_save_quick_grades();
345             $action = 'quickgradingresult';
346         }else if ($action == 'saveoptions') {
347             $this->process_save_grading_options();
348             $action = 'grading';
349         }
351         $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT));
352         $this->register_return_link($action, $returnparams);
354         // now show the right view page
355         if ($action == 'previousgrade') {
356             $mform = null;
357             $o .= $this->view_single_grade_page($mform, -1);
358         } else if ($action == 'quickgradingresult') {
359             $mform = null;
360             $o .= $this->view_quickgrading_result($message);
361         } else if ($action == 'nextgrade') {
362             $mform = null;
363             $o .= $this->view_single_grade_page($mform, 1);
364         } else if ($action == 'grade') {
365             $o .= $this->view_single_grade_page($mform);
366         } else if ($action == 'viewpluginassignfeedback') {
367             $o .= $this->view_plugin_content('assignfeedback');
368         } else if ($action == 'viewpluginassignsubmission') {
369             $o .= $this->view_plugin_content('assignsubmission');
370         } else if ($action == 'editsubmission') {
371             $o .= $this->view_edit_submission_page($mform);
372         } else if ($action == 'grading') {
373             $o .= $this->view_grading_page();
374         } else if ($action == 'downloadall') {
375             $o .= $this->download_submissions();
376         } else if ($action == 'submit') {
377             $o .= $this->check_submit_for_grading();
378         } else {
379             $o .= $this->view_submission_page();
380         }
382         return $o;
383     }
386     /**
387      * Add this instance to the database
388      *
389      * @param stdClass $formdata The data submitted from the form
390      * @param bool $callplugins This is used to skip the plugin code
391      *             when upgrading an old assignment to a new one (the plugins get called manually)
392      * @return mixed false if an error occurs or the int id of the new instance
393      */
394     public function add_instance(stdClass $formdata, $callplugins) {
395         global $DB;
397         $err = '';
399         // add the database record
400         $update = new stdClass();
401         $update->name = $formdata->name;
402         $update->timemodified = time();
403         $update->timecreated = time();
404         $update->course = $formdata->course;
405         $update->courseid = $formdata->course;
406         $update->intro = $formdata->intro;
407         $update->introformat = $formdata->introformat;
408         $update->alwaysshowdescription = $formdata->alwaysshowdescription;
409         $update->preventlatesubmissions = $formdata->preventlatesubmissions;
410         $update->submissiondrafts = $formdata->submissiondrafts;
411         $update->sendnotifications = $formdata->sendnotifications;
412         $update->sendlatenotifications = $formdata->sendlatenotifications;
413         $update->duedate = $formdata->duedate;
414         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
415         $update->grade = $formdata->grade;
416         $returnid = $DB->insert_record('assign', $update);
417         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
418         // cache the course record
419         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
421         if ($callplugins) {
422             // call save_settings hook for submission plugins
423             foreach ($this->submissionplugins as $plugin) {
424                 if (!$this->update_plugin_instance($plugin, $formdata)) {
425                     print_error($plugin->get_error());
426                     return false;
427                 }
428             }
429             foreach ($this->feedbackplugins as $plugin) {
430                 if (!$this->update_plugin_instance($plugin, $formdata)) {
431                     print_error($plugin->get_error());
432                     return false;
433                 }
434             }
436             // in the case of upgrades the coursemodule has not been set so we need to wait before calling these two
437             // TODO: add event to the calendar
438             $this->update_calendar($formdata->coursemodule);
439             // TODO: add the item in the gradebook
440             $this->update_gradebook(false, $formdata->coursemodule);
442         }
444         $update = new stdClass();
445         $update->id = $this->get_instance()->id;
446         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
447         $DB->update_record('assign', $update);
449         return $returnid;
450     }
452     /**
453      * Delete all grades from the gradebook for this assignment
454      *
455      * @return bool
456      */
457     private function delete_grades() {
458         global $CFG;
460         return grade_update('mod/assign', $this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, 0, NULL, array('deleted'=>1)) == GRADE_UPDATE_OK;
461     }
463     /**
464      * Delete this instance from the database
465      *
466      * @return bool false if an error occurs
467      */
468     public function delete_instance() {
469         global $DB;
470         $result = true;
472         foreach ($this->submissionplugins as $plugin) {
473             if (!$plugin->delete_instance()) {
474                 print_error($plugin->get_error());
475                 $result = false;
476             }
477         }
478         foreach ($this->feedbackplugins as $plugin) {
479             if (!$plugin->delete_instance()) {
480                 print_error($plugin->get_error());
481                 $result = false;
482             }
483         }
485         // delete files associated with this assignment
486         $fs = get_file_storage();
487         if (! $fs->delete_area_files($this->context->id) ) {
488             $result = false;
489         }
491         // delete_records will throw an exception if it fails - so no need for error checking here
493         $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
494         $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
495         $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
497         // delete items from the gradebook
498         if (! $this->delete_grades()) {
499             $result = false;
500         }
502         // delete the instance
503         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
505         return $result;
506     }
508     /**
509     * Actual implementation of the reset course functionality, delete all the
510     * assignment submissions for course $data->courseid.
511     *
512     * @param $data the data submitted from the reset course.
513     * @return array status array
514     */
515     public function reset_userdata($data) {
516         global $CFG,$DB;
518         $componentstr = get_string('modulenameplural', 'assign');
519         $status = array();
521         $fs = get_file_storage();
522         if (!empty($data->reset_assign_submissions)) {
523             // Delete files associated with this assignment.
524             foreach ($this->submissionplugins as $plugin) {
525                 $fileareas = array();
526                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
527                 $fileareas = $plugin->get_file_areas();
528                 foreach ($fileareas as $filearea) {
529                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
530                 }
532                 if (!$plugin->delete_instance()) {
533                     $status[] = array('component'=>$componentstr,
534                                       'item'=>get_string('deleteallsubmissions','assign'),
535                                       'error'=>$plugin->get_error());
536                 }
537             }
539             foreach ($this->feedbackplugins as $plugin) {
540                 $fileareas = array();
541                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
542                 $fileareas = $plugin->get_file_areas();
543                 foreach ($fileareas as $filearea) {
544                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
545                 }
547                 if (!$plugin->delete_instance()) {
548                     $status[] = array('component'=>$componentstr,
549                                       'item'=>get_string('deleteallsubmissions','assign'),
550                                       'error'=>$plugin->get_error());
551                 }
552             }
554             $assignssql = "SELECT a.id
555                              FROM {assign} a
556                            WHERE a.course=:course";
557             $params = array ("course" => $data->courseid);
559             $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
560             $status[] = array('component'=>$componentstr,
561                               'item'=>get_string('deleteallsubmissions','assign'),
562                               'error'=>false);
564             if (empty($data->reset_gradebook_grades)) {
565                 // Remove all grades from gradebook.
566                 require_once($CFG->dirroot.'/mod/assign/lib.php');
567                 assign_reset_gradebook($data->courseid);
568             }
569         }
570         // Updating dates - shift may be negative too.
571         if ($data->timeshift) {
572             shift_course_mod_dates('assign',
573                                     array('duedate', 'allowsubmissionsfromdate'),
574                                     $data->timeshift,
575                                     $data->courseid);
576             $status[] = array('component'=>$componentstr,
577                               'item'=>get_string('datechanged'),
578                               'error'=>false);
579         }
581         return $status;
582     }
584     /**
585      * Update the settings for a single plugin
586      *
587      * @param assign_plugin $plugin The plugin to update
588      * @param stdClass $formdata The form data
589      * @return bool false if an error occurs
590      */
591     private function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
592         if ($plugin->is_visible()) {
593             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
594             if ($formdata->$enabledname) {
595                 $plugin->enable();
596                 if (!$plugin->save_settings($formdata)) {
597                     print_error($plugin->get_error());
598                     return false;
599                 }
600             } else {
601                 $plugin->disable();
602             }
603         }
604         return true;
605     }
607     /**
608      * Update the gradebook information for this assignment
609      *
610      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
611      * @param int $coursemoduleid This is required because it might not exist in the database yet
612      * @return bool
613      */
614     public function update_gradebook($reset, $coursemoduleid) {
615          global $CFG;
616         /** Include lib.php */
617         require_once($CFG->dirroot.'/mod/assign/lib.php');
618         $assign = clone $this->get_instance();
619         $assign->cmidnumber = $coursemoduleid;
620         $param = null;
621         if ($reset) {
622             $param = 'reset';
623         }
625         return assign_grade_item_update($assign, $param);
626     }
628     /** Load and cache the admin config for this module
629      *
630      * @return stdClass the plugin config
631      */
632     public function get_admin_config() {
633         if ($this->adminconfig) {
634             return $this->adminconfig;
635         }
636         $this->adminconfig = get_config('assign');
637         return $this->adminconfig;
638     }
641     /**
642      * Update the calendar entries for this assignment
643      *
644      * @param int $coursemoduleid - Required to pass this in because it might not exist in the database yet
645      * @return bool
646      */
647     public function update_calendar($coursemoduleid) {
648         global $DB, $CFG;
649         require_once($CFG->dirroot.'/calendar/lib.php');
651         // special case for add_instance as the coursemodule has not been set yet.
653         if ($this->get_instance()->duedate) {
654             $event = new stdClass();
656             if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id))) {
658                 $event->name        = $this->get_instance()->name;
660                 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
661                 $event->timestart   = $this->get_instance()->duedate;
663                 $calendarevent = calendar_event::load($event->id);
664                 $calendarevent->update($event);
665             } else {
666                 $event = new stdClass();
667                 $event->name        = $this->get_instance()->name;
668                 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
669                 $event->courseid    = $this->get_instance()->course;
670                 $event->groupid     = 0;
671                 $event->userid      = 0;
672                 $event->modulename  = 'assign';
673                 $event->instance    = $this->get_instance()->id;
674                 $event->eventtype   = 'due';
675                 $event->timestart   = $this->get_instance()->duedate;
676                 $event->timeduration = 0;
678                 calendar_event::create($event);
679             }
680         } else {
681             $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id));
682         }
683     }
686     /**
687      * Update this instance in the database
688      *
689      * @param stdClass $formdata - the data submitted from the form
690      * @return bool false if an error occurs
691      */
692     public function update_instance($formdata) {
693         global $DB;
695         $update = new stdClass();
696         $update->id = $formdata->instance;
697         $update->name = $formdata->name;
698         $update->timemodified = time();
699         $update->course = $formdata->course;
700         $update->intro = $formdata->intro;
701         $update->introformat = $formdata->introformat;
702         $update->alwaysshowdescription = $formdata->alwaysshowdescription;
703         $update->preventlatesubmissions = $formdata->preventlatesubmissions;
704         $update->submissiondrafts = $formdata->submissiondrafts;
705         $update->sendnotifications = $formdata->sendnotifications;
706         $update->sendlatenotifications = $formdata->sendlatenotifications;
707         $update->duedate = $formdata->duedate;
708         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
709         $update->grade = $formdata->grade;
711         $result = $DB->update_record('assign', $update);
712         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
714         // load the assignment so the plugins have access to it
716         // call save_settings hook for submission plugins
717         foreach ($this->submissionplugins as $plugin) {
718             if (!$this->update_plugin_instance($plugin, $formdata)) {
719                 print_error($plugin->get_error());
720                 return false;
721             }
722         }
723         foreach ($this->feedbackplugins as $plugin) {
724             if (!$this->update_plugin_instance($plugin, $formdata)) {
725                 print_error($plugin->get_error());
726                 return false;
727             }
728         }
731         // update the database record
734         // update all the calendar events
735         $this->update_calendar($this->get_course_module()->id);
737         $this->update_gradebook(false, $this->get_course_module()->id);
739         $update = new stdClass();
740         $update->id = $this->get_instance()->id;
741         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
742         $DB->update_record('assign', $update);
748         return $result;
749     }
751     /**
752      * add elements in grading plugin form
753      *
754      * @param mixed $grade stdClass|null
755      * @param MoodleQuickForm $mform
756      * @param stdClass $data
757      * @param int $userid - The userid we are grading
758      * @return void
759      */
760     private function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
761         foreach ($this->feedbackplugins as $plugin) {
762             if ($plugin->is_enabled() && $plugin->is_visible()) {
763                 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
764                 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
765                     $mform->removeElement('header_' . $plugin->get_type());
766                 }
767             }
768         }
769     }
773     /**
774      * Add one plugins settings to edit plugin form
775      *
776      * @param assign_plugin $plugin The plugin to add the settings from
777      * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
778      * @return void
779      */
780     private function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform) {
781         global $CFG;
782         if ($plugin->is_visible()) {
783             // enabled
784             //tied disableIf rule to this select element
785             $mform->addElement('selectyesno', $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $plugin->get_name());
786             $mform->addHelpButton($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', 'enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
789             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
790             if ($plugin->get_config('enabled') !== false) {
791                 $default = $plugin->is_enabled();
792             }
793             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
795             $plugin->get_settings($mform);
797         }
799     }
802     /**
803      * Add settings to edit plugin form
804      *
805      * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
806      * @return void
807      */
808     public function add_all_plugin_settings(MoodleQuickForm $mform) {
809         $mform->addElement('header', 'general', get_string('submissionsettings', 'assign'));
811         foreach ($this->submissionplugins as $plugin) {
812             $this->add_plugin_settings($plugin, $mform);
814         }
815         $mform->addElement('header', 'general', get_string('feedbacksettings', 'assign'));
816         foreach ($this->feedbackplugins as $plugin) {
817             $this->add_plugin_settings($plugin, $mform);
818         }
819     }
821     /**
822      * Allow each plugin an opportunity to update the defaultvalues
823      * passed in to the settings form (needed to set up draft areas for
824      * editor and filemanager elements)
825      * @param array $defaultvalues
826      */
827     public function plugin_data_preprocessing(&$defaultvalues) {
828         foreach ($this->submissionplugins as $plugin) {
829             if ($plugin->is_visible()) {
830                 $plugin->data_preprocessing($defaultvalues);
831             }
832         }
833         foreach ($this->feedbackplugins as $plugin) {
834             if ($plugin->is_visible()) {
835                 $plugin->data_preprocessing($defaultvalues);
836             }
837         }
838     }
840     /**
841      * Get the name of the current module.
842      *
843      * @return string the module name (Assignment)
844      */
845     protected function get_module_name() {
846         if (isset(self::$modulename)) {
847             return self::$modulename;
848         }
849         self::$modulename = get_string('modulename', 'assign');
850         return self::$modulename;
851     }
853     /**
854      * Get the plural name of the current module.
855      *
856      * @return string the module name plural (Assignments)
857      */
858     protected function get_module_name_plural() {
859         if (isset(self::$modulenameplural)) {
860             return self::$modulenameplural;
861         }
862         self::$modulenameplural = get_string('modulenameplural', 'assign');
863         return self::$modulenameplural;
864     }
866     /**
867      * Has this assignment been constructed from an instance?
868      *
869      * @return bool
870      */
871     public function has_instance() {
872         return $this->instance || $this->get_course_module();
873     }
875     /**
876      * Get the settings for the current instance of this assignment
877      *
878      * @return stdClass The settings
879      */
880     public function get_instance() {
881         global $DB;
882         if ($this->instance) {
883             return $this->instance;
884         }
885         if ($this->get_course_module()) {
886             $this->instance = $DB->get_record('assign', array('id' => $this->get_course_module()->instance), '*', MUST_EXIST);
887         }
888         if (!$this->instance) {
889             throw new coding_exception('Improper use of the assignment class. Cannot load the assignment record.');
890         }
891         return $this->instance;
892     }
894     /**
895      * Get the context of the current course
896      * @return mixed context|null The course context
897      */
898     public function get_course_context() {
899         if (!$this->context && !$this->course) {
900             throw new coding_exception('Improper use of the assignment class. Cannot load the course context.');
901         }
902         if ($this->context) {
903             return $this->context->get_course_context();
904         } else {
905             return context_course::instance($this->course->id);
906         }
907     }
910     /**
911      * Get the current course module
912      *
913      * @return mixed stdClass|null The course module
914      */
915     public function get_course_module() {
916         if ($this->coursemodule) {
917             return $this->coursemodule;
918         }
919         if (!$this->context) {
920             return null;
921         }
923         if ($this->context->contextlevel == CONTEXT_MODULE) {
924             $this->coursemodule = get_coursemodule_from_id('assign', $this->context->instanceid, 0, false, MUST_EXIST);
925             return $this->coursemodule;
926         }
927         return null;
928     }
930     /**
931      * Get context module
932      *
933      * @return context
934      */
935     public function get_context() {
936         return $this->context;
937     }
939     /**
940      * Get the current course
941      * @return mixed stdClass|null The course
942      */
943     public function get_course() {
944         global $DB;
945         if ($this->course) {
946             return $this->course;
947         }
949         if (!$this->context) {
950             return null;
951         }
952         $this->course = $DB->get_record('course', array('id' => $this->get_course_context()->instanceid), '*', MUST_EXIST);
953         return $this->course;
954     }
956     /**
957      * Return a grade in user-friendly form, whether it's a scale or not
958      *
959      * @param mixed $grade int|null
960      * @param boolean $editing Are we allowing changes to this grade?
961      * @param int $userid The user id the grade belongs to
962      * @param int $modified Timestamp from when the grade was last modified
963      * @return string User-friendly representation of grade
964      */
965     public function display_grade($grade, $editing, $userid=0, $modified=0) {
966         global $DB;
968         static $scalegrades = array();
970         if ($this->get_instance()->grade >= 0) {
971             // Normal number
972             if ($editing && $this->get_instance()->grade > 0) {
973                 if ($grade < 0) {
974                     $displaygrade = '';
975                 } else {
976                     $displaygrade = format_float($grade);
977                 }
978                 $o = '<input type="text" name="quickgrade_' . $userid . '" value="' . $displaygrade . '" size="6" maxlength="10" class="quickgrade"/>';
979                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade,2);
980                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
981                 return $o;
982             } else {
983                 if ($grade == -1 || $grade === null) {
984                     return '-';
985                 } else {
986                     return format_float(($grade),2) .'&nbsp;/&nbsp;'. format_float($this->get_instance()->grade,2);
987                 }
988             }
990         } else {
991             // Scale
992             if (empty($this->cache['scale'])) {
993                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
994                     $this->cache['scale'] = make_menu_from_list($scale->scale);
995                 } else {
996                     return '-';
997                 }
998             }
999             if ($editing) {
1000                 $o = '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1001                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1002                 foreach ($this->cache['scale'] as $optionid => $option) {
1003                     $selected = '';
1004                     if ($grade == $optionid) {
1005                         $selected = 'selected="selected"';
1006                     }
1007                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1008                 }
1009                 $o .= '</select>';
1010                 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1011                 return $o;
1012             } else {
1013                 $scaleid = (int)$grade;
1014                 if (isset($this->cache['scale'][$scaleid])) {
1015                     return $this->cache['scale'][$scaleid];
1016                 }
1017                 return '-';
1018             }
1019         }
1020     }
1022     /**
1023      * Load a list of users enrolled in the current course with the specified permission and group (0 for no group)
1024      *
1025      * @param int $currentgroup
1026      * @param bool $idsonly
1027      * @return array List of user records
1028      */
1029     public function list_participants($currentgroup, $idsonly) {
1030         if ($idsonly) {
1031             return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup, 'u.id');
1032         } else {
1033             return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1034         }
1035     }
1037     /**
1038      * Load a count of users enrolled in the current course with the specified permission and group (0 for no group)
1039      *
1040      * @param int $currentgroup
1041      * @return int number of matching users
1042      */
1043     public function count_participants($currentgroup) {
1044         return count_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1045     }
1047     /**
1048      * Load a count of users submissions in the current module that require grading
1049      * This means the submission modification time is more recent than the
1050      * grading modification time.
1051      *
1052      * @return int number of matching submissions
1053      */
1054     public function count_submissions_need_grading() {
1055         global $DB;
1057         $params = array($this->get_course_module()->instance);
1059         return $DB->count_records_sql("SELECT COUNT('x')
1060                                        FROM {assign_submission} s
1061                                        LEFT JOIN {assign_grades} g ON s.assignment = g.assignment AND s.userid = g.userid
1062                                        WHERE s.assignment = ?
1063                                            AND s.timemodified IS NOT NULL
1064                                            AND (s.timemodified > g.timemodified OR g.timemodified IS NULL)",
1065                                        $params);
1066     }
1068     /**
1069      * Load a count of users enrolled in the current course with the specified permission and group (optional)
1070      *
1071      * @param string $status The submission status - should match one of the constants
1072      * @return int number of matching submissions
1073      */
1074     public function count_submissions_with_status($status) {
1075         global $DB;
1076         return $DB->count_records_sql("SELECT COUNT('x')
1077                                      FROM {assign_submission}
1078                                     WHERE assignment = ? AND
1079                                           status = ?", array($this->get_course_module()->instance, $status));
1080     }
1082     /**
1083      * Utility function to get the userid for every row in the grading table
1084      * so the order can be frozen while we iterate it
1085      *
1086      * @return array An array of userids
1087      */
1088     private function get_grading_userid_list(){
1089         $filter = get_user_preferences('assign_filter', '');
1090         $table = new assign_grading_table($this, 0, $filter, 0, false);
1092         $useridlist = $table->get_column_data('userid');
1094         return $useridlist;
1095     }
1098     /**
1099      * Utility function get the userid based on the row number of the grading table.
1100      * This takes into account any active filters on the table.
1101      *
1102      * @param int $num The row number of the user
1103      * @param bool $last This is set to true if this is the last user in the table
1104      * @return mixed The user id of the matching user or false if there was an error
1105      */
1106     private function get_userid_for_row($num, $last){
1107         if (!array_key_exists('userid_for_row', $this->cache)) {
1108             $this->cache['userid_for_row'] = array();
1109         }
1110         if (array_key_exists($num, $this->cache['userid_for_row'])) {
1111             list($userid, $last) = $this->cache['userid_for_row'][$num];
1112             return $userid;
1113         }
1115         $filter = get_user_preferences('assign_filter', '');
1116         $table = new assign_grading_table($this, 0, $filter, 0, false);
1118         $userid = $table->get_cell_data($num, 'userid', $last);
1120         $this->cache['userid_for_row'][$num] = array($userid, $last);
1121         return $userid;
1122     }
1124     /**
1125      * Return all assignment submissions by ENROLLED students (even empty)
1126      *
1127      * @param string $sort optional field names for the ORDER BY in the sql query
1128      * @param string $dir optional specifying the sort direction, defaults to DESC
1129      * @return array The submission objects indexed by id
1130      */
1131     private function get_all_submissions( $sort="", $dir="DESC") {
1132         global $CFG, $DB;
1134         if ($sort == "lastname" or $sort == "firstname") {
1135             $sort = "u.$sort $dir";
1136         } else if (empty($sort)) {
1137             $sort = "a.timemodified DESC";
1138         } else {
1139             $sort = "a.$sort $dir";
1140         }
1142         return $DB->get_records_sql("SELECT a.*
1143                                        FROM {assign_submission} a, {user} u
1144                                       WHERE u.id = a.userid
1145                                             AND a.assignment = ?
1146                                    ORDER BY $sort", array($this->get_instance()->id));
1148     }
1150     /**
1151      * Generate zip file from array of given files
1152      *
1153      * @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
1154      * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
1155      */
1156      private function pack_files($filesforzipping) {
1157          global $CFG;
1158          //create path for new zip file.
1159          $tempzip = tempnam($CFG->tempdir.'/', 'assignment_');
1160          //zip files
1161          $zipper = new zip_packer();
1162          if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1163              return $tempzip;
1164          }
1165          return false;
1166     }
1168     /**
1169      * Finds all assignment notifications that have yet to be mailed out, and mails them.
1170      *
1171      * Cron function to be run periodically according to the moodle cron
1172      *
1173      * @return bool
1174      */
1175     static function cron() {
1176         global $DB;
1178         // only ever send a max of one days worth of updates
1179         $yesterday = time() - (24 * 3600);
1180         $timenow   = time();
1182         // Collect all submissions from the past 24 hours that require mailing.
1183         $sql = "SELECT s.*, a.course, a.name, g.*, g.id as gradeid, g.timemodified as lastmodified
1184                  FROM {assign} a
1185                  JOIN {assign_grades} g ON g.assignment = a.id
1186             LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1187                 WHERE g.timemodified >= :yesterday AND
1188                       g.timemodified <= :today AND
1189                       g.mailed = 0";
1190         $params = array('yesterday' => $yesterday, 'today' => $timenow);
1191         $submissions = $DB->get_records_sql($sql, $params);
1193         if (empty($submissions)) {
1194             mtrace('done.');
1195             return true;
1196         }
1198         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1200         // Preload courses we are going to need those.
1201         $courseids = array();
1202         foreach ($submissions as $submission) {
1203             $courseids[] = $submission->course;
1204         }
1205         // Filter out duplicates
1206         $courseids = array_unique($courseids);
1207         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1208         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1209         $sql = "SELECT c.*, {$ctxselect}
1210                   FROM {course} c
1211              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1212                  WHERE c.id {$courseidsql}";
1213         $params['contextlevel'] = CONTEXT_COURSE;
1214         $courses = $DB->get_records_sql($sql, $params);
1215         // Clean up... this could go on for a while.
1216         unset($courseids);
1217         unset($ctxselect);
1218         unset($courseidsql);
1219         unset($params);
1221         // Simple array we'll use for caching modules.
1222         $modcache = array();
1224         // Message students about new feedback
1225         foreach ($submissions as $submission) {
1227             mtrace("Processing assignment submission $submission->id ...");
1229             // do not cache user lookups - could be too many
1230             if (!$user = $DB->get_record("user", array("id"=>$submission->userid))) {
1231                 mtrace("Could not find user $submission->userid");
1232                 continue;
1233             }
1235             // use a cache to prevent the same DB queries happening over and over
1236             if (!array_key_exists($submission->course, $courses)) {
1237                 mtrace("Could not find course $submission->course");
1238                 continue;
1239             }
1240             $course = $courses[$submission->course];
1241             if (isset($course->ctxid)) {
1242                 // Context has not yet been preloaded. Do so now.
1243                 context_helper::preload_from_record($course);
1244             }
1246             // Override the language and timezone of the "current" user, so that
1247             // mail is customised for the receiver.
1248             cron_setup_user($user, $course);
1250             // context lookups are already cached
1251             $coursecontext = context_course::instance($course->id);
1252             if (!is_enrolled($coursecontext, $user->id)) {
1253                 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
1254                 mtrace(fullname($user)." not an active participant in " . $courseshortname);
1255                 continue;
1256             }
1258             if (!$grader = $DB->get_record("user", array("id"=>$submission->grader))) {
1259                 mtrace("Could not find grader $submission->grader");
1260                 continue;
1261             }
1263             if (!array_key_exists($submission->assignment, $modcache)) {
1264                 if (! $mod = get_coursemodule_from_instance("assign", $submission->assignment, $course->id)) {
1265                     mtrace("Could not find course module for assignment id $submission->assignment");
1266                     continue;
1267                 }
1268                 $modcache[$submission->assignment] = $mod;
1269             } else {
1270                 $mod = $modcache[$submission->assignment];
1271             }
1272             // context lookups are already cached
1273             $contextmodule = context_module::instance($mod->id);
1275             if (!$mod->visible) {
1276                 // Hold mail notification for hidden assignments until later
1277                 continue;
1278             }
1280             // need to send this to the student
1281             $messagetype = 'feedbackavailable';
1282             $eventtype = 'assign_notification';
1283             $updatetime = $submission->lastmodified;
1284             $modulename = get_string('modulename', 'assign');
1285             self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime, $mod, $contextmodule, $course, $modulename, $submission->name);
1287             $grade = new stdClass();
1288             $grade->id = $submission->gradeid;
1289             $grade->mailed = 1;
1290             $DB->update_record('assign_grades', $grade);
1292             mtrace('Done');
1293         }
1294         mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1296         cron_setup_user();
1298         // Free up memory just to be sure
1299         unset($courses);
1300         unset($modcache);
1302         return true;
1303     }
1305     /**
1306      * Update a grade in the grade table for the assignment and in the gradebook
1307      *
1308      * @param stdClass $grade a grade record keyed on id
1309      * @return bool true for success
1310      */
1311     private function update_grade($grade) {
1312         global $DB;
1314         $grade->timemodified = time();
1316         if ($grade->grade && $grade->grade != -1) {
1317             if ($this->get_instance()->grade > 0) {
1318                 if (!is_numeric($grade->grade)) {
1319                     return false;
1320                 } else if ($grade->grade > $this->get_instance()->grade) {
1321                     return false;
1322                 } else if ($grade->grade < 0) {
1323                     return false;
1324                 }
1325             } else {
1326                 // this is a scale
1327                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1328                     $scaleoptions = make_menu_from_list($scale->scale);
1329                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1330                         return false;
1331                     }
1332                 }
1333             }
1334         }
1336         $result = $DB->update_record('assign_grades', $grade);
1337         if ($result) {
1338             $this->gradebook_item_update(null, $grade);
1339         }
1340         return $result;
1341     }
1343     /**
1344      * display the submission that is used by a plugin
1345      * Uses url parameters 'sid', 'gid' and 'plugin'
1346      * @param string $pluginsubtype
1347      * @return string
1348      */
1349     private function view_plugin_content($pluginsubtype) {
1350         global $USER;
1352         $o = '';
1354         $submissionid = optional_param('sid', 0, PARAM_INT);
1355         $gradeid = optional_param('gid', 0, PARAM_INT);
1356         $plugintype = required_param('plugin', PARAM_TEXT);
1357         $item = null;
1358         if ($pluginsubtype == 'assignsubmission') {
1359             $plugin = $this->get_submission_plugin_by_type($plugintype);
1360             if ($submissionid <= 0) {
1361                 throw new coding_exception('Submission id should not be 0');
1362             }
1363             $item = $this->get_submission($submissionid);
1365             // permissions
1366             if ($item->userid != $USER->id) {
1367                 require_capability('mod/assign:grade', $this->context);
1368             }
1369             $o .= $this->output->render(new assign_header($this->get_instance(),
1370                                                               $this->get_context(),
1371                                                               $this->show_intro(),
1372                                                               $this->get_course_module()->id,
1373                                                               $plugin->get_name()));
1374             $o .= $this->output->render(new assign_submission_plugin_submission($plugin,
1375                                                               $item,
1376                                                               assign_submission_plugin_submission::FULL,
1377                                                               $this->get_course_module()->id,
1378                                                               $this->get_return_action(),
1379                                                               $this->get_return_params()));
1381             $this->add_to_log('view submission', get_string('viewsubmissionforuser', 'assign', $item->userid));
1382         } else {
1383             $plugin = $this->get_feedback_plugin_by_type($plugintype);
1384             if ($gradeid <= 0) {
1385                 throw new coding_exception('Grade id should not be 0');
1386             }
1387             $item = $this->get_grade($gradeid);
1388             // permissions
1389             if ($item->userid != $USER->id) {
1390                 require_capability('mod/assign:grade', $this->context);
1391             }
1392             $o .= $this->output->render(new assign_header($this->get_instance(),
1393                                                               $this->get_context(),
1394                                                               $this->show_intro(),
1395                                                               $this->get_course_module()->id,
1396                                                               $plugin->get_name()));
1397             $o .= $this->output->render(new assign_feedback_plugin_feedback($plugin,
1398                                                               $item,
1399                                                               assign_feedback_plugin_feedback::FULL,
1400                                                               $this->get_course_module()->id,
1401                                                               $this->get_return_action(),
1402                                                               $this->get_return_params()));
1403             $this->add_to_log('view feedback', get_string('viewfeedbackforuser', 'assign', $item->userid));
1404         }
1407         $o .= $this->view_return_links();
1409         $o .= $this->view_footer();
1410         return $o;
1411     }
1413     /**
1414      * render the content in editor that is often used by plugin
1415      *
1416      * @param string $filearea
1417      * @param int  $submissionid
1418      * @param string $plugintype
1419      * @param string $editor
1420      * @param string $component
1421      * @return string
1422      */
1423     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1424         global $CFG;
1426         $result = '';
1428         $plugin = $this->get_submission_plugin_by_type($plugintype);
1430         $text = $plugin->get_editor_text($editor, $submissionid);
1431         $format = $plugin->get_editor_format($editor, $submissionid);
1433         $finaltext = file_rewrite_pluginfile_urls($text, 'pluginfile.php', $this->get_context()->id, $component, $filearea, $submissionid);
1434         $result .= format_text($finaltext, $format, array('overflowdiv' => true, 'context' => $this->get_context()));
1438         if ($CFG->enableportfolios) {
1439             require_once($CFG->libdir . '/portfoliolib.php');
1441             $button = new portfolio_add_button();
1442             $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');
1443             $fs = get_file_storage();
1445             if ($files = $fs->get_area_files($this->context->id, $component,$filearea, $submissionid, "timemodified", false)) {
1446                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1447             } else {
1448                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1449             }
1450             $result .= $button->to_html();
1451         }
1452         return $result;
1453     }
1455     /**
1456      * Display a grading error
1457      *
1458      * @param string $message - The description of the result
1459      * @return string
1460      */
1461     private function view_quickgrading_result($message) {
1462         $o = '';
1463         $o .= $this->output->render(new assign_header($this->get_instance(),
1464                                                       $this->get_context(),
1465                                                       $this->show_intro(),
1466                                                       $this->get_course_module()->id,
1467                                                       get_string('quickgradingresult', 'assign')));
1468         $o .= $this->output->render(new assign_quickgrading_result($message, $this->get_course_module()->id));
1469         $o .= $this->view_footer();
1470         return $o;
1471     }
1473     /**
1474      * Display the page footer
1475      *
1476      * @return string
1477      */
1478     private function view_footer() {
1479         return $this->output->render_footer();
1480     }
1482     /**
1483      * Does this user have grade permission for this assignment
1484      *
1485      * @return bool
1486      */
1487     private function can_grade() {
1488         // Permissions check
1489         if (!has_capability('mod/assign:grade', $this->context)) {
1490             return false;
1491         }
1493         return true;
1494     }
1496     /**
1497      * Download a zip file of all assignment submissions
1498      *
1499      * @return void
1500      */
1501     private function download_submissions() {
1502         global $CFG,$DB;
1504         // more efficient to load this here
1505         require_once($CFG->libdir.'/filelib.php');
1507         // load all submissions
1508         $submissions = $this->get_all_submissions('','');
1510         if (empty($submissions)) {
1511             print_error('errornosubmissions', 'assign');
1512             return;
1513         }
1515         // build a list of files to zip
1516         $filesforzipping = array();
1517         $fs = get_file_storage();
1519         $groupmode = groups_get_activity_groupmode($this->get_course_module());
1520         $groupid = 0;   // All users
1521         $groupname = '';
1522         if ($groupmode) {
1523             $groupid = groups_get_activity_group($this->get_course_module(), true);
1524             $groupname = groups_get_group_name($groupid).'-';
1525         }
1527         // construct the zip file name
1528         $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.
1530         // get all the files for each submission
1531         foreach ($submissions as $submission) {
1532             $userid = $submission->userid; //get userid
1533             if ((groups_is_member($groupid,$userid) or !$groupmode or !$groupid)) {
1534                 // get the plugins to add their own files to the zip
1536                 $user = $DB->get_record("user", array("id"=>$userid),'id,username,firstname,lastname', MUST_EXIST);
1538                 $prefix = clean_filename(fullname($user) . "_" .$userid . "_");
1540                 foreach ($this->submissionplugins as $plugin) {
1541                     if ($plugin->is_enabled() && $plugin->is_visible()) {
1542                         $pluginfiles = $plugin->get_files($submission);
1545                         foreach ($pluginfiles as $zipfilename => $file) {
1546                             $filesforzipping[$prefix . $zipfilename] = $file;
1547                         }
1548                     }
1549                 }
1551             }
1552         } // end of foreach loop
1553         if ($zipfile = $this->pack_files($filesforzipping)) {
1554             $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
1555             send_temp_file($zipfile, $filename); //send file and delete after sending.
1556         }
1557     }
1559     /**
1560      * Util function to add a message to the log
1561      *
1562      * @param string $action The current action
1563      * @param string $info A detailed description of the change. But no more than 255 characters.
1564      * @param string $url The url to the assign module instance.
1565      * @return void
1566      */
1567     public function add_to_log($action = '', $info = '', $url='') {
1568         global $USER;
1570         $fullurl = 'view.php?id=' . $this->get_course_module()->id;
1571         if ($url != '') {
1572             $fullurl .= '&' . $url;
1573         }
1575         add_to_log($this->get_course()->id, 'assign', $action, $fullurl, $info, $this->get_course_module()->id, $USER->id);
1576     }
1578     /**
1579      * Load the submission object for a particular user, optionally creating it if required
1580      *
1581      * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
1582      * @param bool $create optional Defaults to false. If set to true a new submission object will be created in the database
1583      * @return stdClass The submission
1584      */
1585     private function get_user_submission($userid, $create) {
1586         global $DB, $USER;
1588         if (!$userid) {
1589             $userid = $USER->id;
1590         }
1591         // if the userid is not null then use userid
1592         $submission = $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1594         if ($submission) {
1595             return $submission;
1596         }
1597         if ($create) {
1598             $submission = new stdClass();
1599             $submission->assignment   = $this->get_instance()->id;
1600             $submission->userid       = $userid;
1601             $submission->timecreated = time();
1602             $submission->timemodified = $submission->timecreated;
1604             if ($this->get_instance()->submissiondrafts) {
1605                 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1606             } else {
1607                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1608             }
1609             $sid = $DB->insert_record('assign_submission', $submission);
1610             $submission->id = $sid;
1611             return $submission;
1612         }
1613         return false;
1614     }
1616     /**
1617      * Load the submission object from it's id
1618      *
1619      * @param int $submissionid The id of the submission we want
1620      * @return stdClass The submission
1621      */
1622     private function get_submission($submissionid) {
1623         global $DB;
1625         return $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid), '*', MUST_EXIST);
1626     }
1628     /**
1629      * This will retrieve a grade object from the db, optionally creating it if required
1630      *
1631      * @param int $userid The user we are grading
1632      * @param bool $create If true the grade will be created if it does not exist
1633      * @return stdClass The grade record
1634      */
1635     private function get_user_grade($userid, $create) {
1636         global $DB, $USER;
1638         if (!$userid) {
1639             $userid = $USER->id;
1640         }
1642         // if the userid is not null then use userid
1643         $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1645         if ($grade) {
1646             return $grade;
1647         }
1648         if ($create) {
1649             $grade = new stdClass();
1650             $grade->assignment   = $this->get_instance()->id;
1651             $grade->userid       = $userid;
1652             $grade->timecreated = time();
1653             $grade->timemodified = $grade->timecreated;
1654             $grade->locked = 0;
1655             $grade->grade = -1;
1656             $grade->grader = $USER->id;
1657             $gid = $DB->insert_record('assign_grades', $grade);
1658             $grade->id = $gid;
1659             return $grade;
1660         }
1661         return false;
1662     }
1664     /**
1665      * This will retrieve a grade object from the db
1666      *
1667      * @param int $gradeid The id of the grade
1668      * @return stdClass The grade record
1669      */
1670     private function get_grade($gradeid) {
1671         global $DB;
1673         return $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid), '*', MUST_EXIST);
1674     }
1676     /**
1677      * Print the grading page for a single user submission
1678      *
1679      * @param moodleform $mform
1680      * @param int $offset
1681      * @return string
1682      */
1683     private function view_single_grade_page($mform, $offset=0) {
1684         global $DB, $CFG;
1686         $o = '';
1688         // Include grade form
1689         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1691         // Need submit permission to submit an assignment
1692         require_capability('mod/assign:grade', $this->context);
1694         $o .= $this->output->render(new assign_header($this->get_instance(),
1695                                                       $this->get_context(), false, $this->get_course_module()->id,get_string('grading', 'assign')));
1697         $rownum = required_param('rownum', PARAM_INT) + $offset;
1698         $useridlist = optional_param('useridlist', '', PARAM_TEXT);
1699         if ($useridlist) {
1700             $useridlist = explode(',', $useridlist);
1701         } else {
1702             $useridlist = $this->get_grading_userid_list();
1703         }
1704         $last = false;
1705         $userid = $useridlist[$rownum];
1706         if ($rownum == count($useridlist) - 1) {
1707             $last = true;
1708         }
1709         if (!$userid) {
1710             throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
1711         }
1712         $user = $DB->get_record('user', array('id' => $userid));
1713         if ($user) {
1714             $o .= $this->output->render(new assign_user_summary($user, $this->get_course()->id, has_capability('moodle/site:viewfullnames', $this->get_course_context())));
1715         }
1716         $submission = $this->get_user_submission($userid, false);
1717         // get the current grade
1718         $grade = $this->get_user_grade($userid, false);
1719         if ($this->can_view_submission($userid)) {
1720             $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
1721             $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
1722                                                               $this->get_instance()->alwaysshowdescription,
1723                                                               $submission,
1724                                                               $this->is_any_submission_plugin_enabled(),
1725                                                               $gradelocked,
1726                                                               $this->is_graded($userid),
1727                                                               $this->get_instance()->duedate,
1728                                                               $this->get_submission_plugins(),
1729                                                               $this->get_return_action(),
1730                                                               $this->get_return_params(),
1731                                                               $this->get_course_module()->id,
1732                                                               assign_submission_status::GRADER_VIEW,
1733                                                               false,
1734                                                               false));
1735         }
1736         if ($grade) {
1737             $data = new stdClass();
1738             if ($grade->grade !== NULL && $grade->grade >= 0) {
1739                 $data->grade = format_float($grade->grade,2);
1740             }
1741         } else {
1742             $data = new stdClass();
1743             $data->grade = '';
1744         }
1746         // now show the grading form
1747         if (!$mform) {
1748             $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last)), 'post', '', array('class'=>'gradeform'));
1749         }
1750         $o .= $this->output->render(new assign_form('gradingform',$mform));
1752         $this->add_to_log('view grading form', get_string('viewgradingformforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
1754         $o .= $this->view_footer();
1755         return $o;
1756     }
1760     /**
1761      * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
1762      *
1763      * @return string
1764      */
1765     private function view_return_links() {
1767         $returnaction = optional_param('returnaction','', PARAM_ALPHA);
1768         $returnparams = optional_param('returnparams','', PARAM_TEXT);
1770         $params = array();
1771         parse_str($returnparams, $params);
1772         $params = array_merge( array('id' => $this->get_course_module()->id, 'action' => $returnaction), $params);
1774         return $this->output->single_button(new moodle_url('/mod/assign/view.php', $params), get_string('back'), 'get');
1776     }
1778     /**
1779      * View the grading table of all submissions for this assignment
1780      *
1781      * @return string
1782      */
1783     private function view_grading_table() {
1784         global $USER, $CFG;
1785         // Include grading options form
1786         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
1787         require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
1788         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1789         $o = '';
1791         $links = array();
1792         if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
1793                 has_capability('moodle/grade:viewall', $this->get_course_context())) {
1794             $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
1795             $links[$gradebookurl] = get_string('viewgradebook', 'assign');
1796         }
1797         if ($this->is_any_submission_plugin_enabled()) {
1798             $downloadurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=downloadall';
1799             $links[$downloadurl] = get_string('downloadall', 'assign');
1800         }
1802         $gradingactions = new url_select($links);
1804         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
1806         $perpage = get_user_preferences('assign_perpage', 10);
1807         $filter = get_user_preferences('assign_filter', '');
1808         $controller = $gradingmanager->get_active_controller();
1809         $showquickgrading = empty($controller);
1810         if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
1811             $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
1812             set_user_preference('assign_quickgrading', $quickgrading);
1813         }
1814         $quickgrading = get_user_preferences('assign_quickgrading', false);
1816         // print options  for changing the filter and changing the number of results per page
1817         $gradingoptionsform = new mod_assign_grading_options_form(null,
1818                                                                   array('cm'=>$this->get_course_module()->id,
1819                                                                         'contextid'=>$this->context->id,
1820                                                                         'userid'=>$USER->id,
1821                                                                         'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
1822                                                                         'showquickgrading'=>$showquickgrading,
1823                                                                         'quickgrading'=>$quickgrading),
1824                                                                   'post', '',
1825                                                                   array('class'=>'gradingoptionsform'));
1827         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1828                                                                   array('cm'=>$this->get_course_module()->id,
1829                                                                         'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1830                                                                   'post', '',
1831                                                                   array('class'=>'gradingbatchoperationsform'));
1833         $gradingoptionsdata = new stdClass();
1834         $gradingoptionsdata->perpage = $perpage;
1835         $gradingoptionsdata->filter = $filter;
1836         $gradingoptionsform->set_data($gradingoptionsdata);
1838         $actionformtext = $this->output->render($gradingactions);
1839         $o .= $this->output->render(new assign_header($this->get_instance(),
1840                                                       $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign'), $actionformtext));
1841         $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);
1843         // plagiarism update status apearring in the grading book
1844         if (!empty($CFG->enableplagiarism)) {
1845             /** Include plagiarismlib.php */
1846             require_once($CFG->libdir . '/plagiarismlib.php');
1847             $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
1848         }
1850         // load and print the table of submissions
1851         if ($showquickgrading && $quickgrading) {
1852             $table = $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, true));
1853             $quickgradingform = new mod_assign_quick_grading_form(null,
1854                                                                   array('cm'=>$this->get_course_module()->id,
1855                                                                         'gradingtable'=>$table));
1856             $o .= $this->output->render(new assign_form('quickgradingform', $quickgradingform));
1857         } else {
1858             $o .= $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, false));
1859         }
1861         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1862         $users = array_keys($this->list_participants($currentgroup, true));
1863         if (count($users) != 0) {
1864             // if no enrolled user in a course then don't display the batch operations feature
1865             $o .= $this->output->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
1866         }
1867         $o .= $this->output->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
1868         return $o;
1869     }
1871     /**
1872      * View entire grading page.
1873      *
1874      * @return string
1875      */
1876     private function view_grading_page() {
1877         global $CFG;
1879         $o = '';
1880         // Need submit permission to submit an assignment
1881         require_capability('mod/assign:grade', $this->context);
1882         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1884         // only load this if it is
1886         $o .= $this->view_grading_table();
1888         $o .= $this->view_footer();
1889         $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
1890         return $o;
1891     }
1893     /**
1894      * Capture the output of the plagiarism plugins disclosures and return it as a string
1895      *
1896      * @return void
1897      */
1898     private function plagiarism_print_disclosure() {
1899         global $CFG;
1900         $o = '';
1902         if (!empty($CFG->enableplagiarism)) {
1903             /** Include plagiarismlib.php */
1904             require_once($CFG->libdir . '/plagiarismlib.php');
1906             $o .= plagiarism_print_disclosure($this->get_course_module()->id);
1907         }
1909         return $o;
1910     }
1912     /**
1913      * message for students when assignment submissions have been closed
1914      *
1915      * @return string
1916      */
1917     private function view_student_error_message() {
1918         global $CFG;
1920         $o = '';
1921         // Need submit permission to submit an assignment
1922         require_capability('mod/assign:submit', $this->context);
1924         $o .= $this->output->render(new assign_header($this->get_instance(),
1925                                                       $this->get_context(),
1926                                                       $this->show_intro(),
1927                                                       $this->get_course_module()->id,
1928                                                       get_string('editsubmission', 'assign')));
1930         $o .= $this->output->notification(get_string('submissionsclosed', 'assign'));
1932         $o .= $this->view_footer();
1934         return $o;
1936     }
1938     /**
1939      * View edit submissions page.
1940      *
1941      * @param moodleform $mform
1942      * @return void
1943      */
1944     private function view_edit_submission_page($mform) {
1945         global $CFG;
1947         $o = '';
1948         // Include submission form
1949         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
1950         // Need submit permission to submit an assignment
1951         require_capability('mod/assign:submit', $this->context);
1953         if (!$this->submissions_open()) {
1954             return $this->view_student_error_message();
1955         }
1956         $o .= $this->output->render(new assign_header($this->get_instance(),
1957                                                       $this->get_context(),
1958                                                       $this->show_intro(),
1959                                                       $this->get_course_module()->id,
1960                                                       get_string('editsubmission', 'assign')));
1961         $o .= $this->plagiarism_print_disclosure();
1962         $data = new stdClass();
1964         if (!$mform) {
1965             $mform = new mod_assign_submission_form(null, array($this, $data));
1966         }
1968         $o .= $this->output->render(new assign_form('editsubmissionform',$mform));
1970         $o .= $this->view_footer();
1971         $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
1973         return $o;
1974     }
1976     /**
1977      * See if this assignment has a grade yet
1978      *
1979      * @param int $userid
1980      * @return bool
1981      */
1982     private function is_graded($userid) {
1983         $grade = $this->get_user_grade($userid, false);
1984         if ($grade) {
1985             return ($grade->grade !== NULL && $grade->grade >= 0);
1986         }
1987         return false;
1988     }
1991     /**
1992      * Perform an access check to see if the current $USER can view this users submission
1993      *
1994      * @param int $userid
1995      * @return bool
1996      */
1997     public function can_view_submission($userid) {
1998         global $USER;
2000         if (!is_enrolled($this->get_course_context(), $userid)) {
2001             return false;
2002         }
2003         if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
2004             return false;
2005         }
2006         if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
2007             return false;
2008         }
2009         return true;
2010     }
2012     /**
2013      * Ask the user to confirm they want to perform this batch operation
2014      * @return string
2015      */
2016     private function process_batch_grading_operation() {
2017         global $CFG;
2018         require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2019         require_sesskey();
2021         $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2022                                                                   array('cm'=>$this->get_course_module()->id,
2023                                                                         'submissiondrafts'=>$this->get_instance()->submissiondrafts),
2024                                                                   'post', '',
2025                                                                   array('class'=>'gradingbatchoperationsform'));
2027         if ($data = $gradingbatchoperationsform->get_data()) {
2028             // get the list of users
2029             $users = $data->selectedusers;
2030             $userlist = explode(',', $users);
2032             foreach ($userlist as $userid) {
2033                 if ($data->operation == 'lock') {
2034                     $this->process_lock($userid);
2035                 } else if ($data->operation == 'unlock') {
2036                     $this->process_unlock($userid);
2037                 } else if ($data->operation == 'reverttodraft') {
2038                     $this->process_revert_to_draft($userid);
2039                 }
2040             }
2041         }
2043         return true;
2044     }
2046     /**
2047      * Ask the user to confirm they want to submit their work for grading
2048      * @return string
2049      */
2050     private function check_submit_for_grading() {
2051         global $USER;
2052         // Check that all of the submission plugins are ready for this submission
2053         $notifications = array();
2054         $submission = $this->get_user_submission($USER->id, false);
2055         $plugins = $this->get_submission_plugins();
2056         foreach ($plugins as $plugin) {
2057             if ($plugin->is_enabled() && $plugin->is_visible()) {
2058                 $check = $plugin->precheck_submission($submission);
2059                 if ($check !== true) {
2060                     $notifications[] = $check;
2061                 }
2062             }
2063         }
2065         $o = '';
2066         $o .= $this->output->header();
2067         $o .= $this->output->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id));
2068         $o .= $this->view_footer();
2069         return $o;
2070     }
2072     /**
2073      * Print 2 tables of information with no action links -
2074      * the submission summary and the grading summary
2075      *
2076      * @param stdClass $user the user to print the report for
2077      * @param bool $showlinks - Return plain text or links to the profile
2078      * @return string - the html summary
2079      */
2080     public function view_student_summary($user, $showlinks) {
2081         global $CFG, $DB, $PAGE;
2083         $grade = $this->get_user_grade($user->id, false);
2084         $submission = $this->get_user_submission($user->id, false);
2085         $o = '';
2087         if ($this->can_view_submission($user->id)) {
2088             $showedit = has_capability('mod/assign:submit', $this->context) &&
2089                          $this->submissions_open() && ($this->is_any_submission_plugin_enabled()) && $showlinks;
2090             $showsubmit = $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT) && $showlinks;
2091             $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
2093             $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
2094                                                               $this->get_instance()->alwaysshowdescription,
2095                                                               $submission,
2096                                                               $this->is_any_submission_plugin_enabled(),
2097                                                               $gradelocked,
2098                                                               $this->is_graded($user->id),
2099                                                               $this->get_instance()->duedate,
2100                                                               $this->get_submission_plugins(),
2101                                                               $this->get_return_action(),
2102                                                               $this->get_return_params(),
2103                                                               $this->get_course_module()->id,
2104                                                               assign_submission_status::STUDENT_VIEW,
2105                                                               $showedit,
2106                                                               $showsubmit));
2107             require_once($CFG->libdir.'/gradelib.php');
2108             require_once($CFG->dirroot.'/grade/grading/lib.php');
2110             $gradinginfo = grade_get_grades($this->get_course()->id,
2111                                         'mod',
2112                                         'assign',
2113                                         $this->get_instance()->id,
2114                                         $user->id);
2116             $gradingitem = $gradinginfo->items[0];
2117             $gradebookgrade = $gradingitem->grades[$user->id];
2119             // check to see if all feedback plugins are empty
2120             $emptyplugins = true;
2121             if ($grade) {
2122                 foreach ($this->get_feedback_plugins() as $plugin) {
2123                     if ($plugin->is_visible() && $plugin->is_enabled()) {
2124                         if (!$plugin->is_empty($grade)) {
2125                             $emptyplugins = false;
2126                         }
2127                     }
2128                 }
2129             }
2132             if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
2134                 $gradefordisplay = '';
2135                 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2137                 if ($controller = $gradingmanager->get_active_controller()) {
2138                     $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
2139                     $gradefordisplay = $controller->render_grade($PAGE,
2140                                                                  $grade->id,
2141                                                                  $gradingitem,
2142                                                                  $gradebookgrade->str_long_grade,
2143                                                                  has_capability('mod/assign:grade', $this->get_context()));
2144                 } else {
2145                     $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
2146                 }
2148                 $gradeddate = $gradebookgrade->dategraded;
2149                 $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));
2151                 $feedbackstatus = new assign_feedback_status($gradefordisplay,
2152                                                       $gradeddate,
2153                                                       $grader,
2154                                                       $this->get_feedback_plugins(),
2155                                                       $grade,
2156                                                       $this->get_course_module()->id,
2157                                                       $this->get_return_action(),
2158                                                       $this->get_return_params());
2160                 $o .= $this->output->render($feedbackstatus);
2161             }
2163         }
2164         return $o;
2165     }
2167     /**
2168      * View submissions page (contains details of current submission).
2169      *
2170      * @return string
2171      */
2172     private function view_submission_page() {
2173         global $CFG, $DB, $USER, $PAGE;
2175         $o = '';
2176         $o .= $this->output->render(new assign_header($this->get_instance(),
2177                                                       $this->get_context(),
2178                                                       $this->show_intro(),
2179                                                       $this->get_course_module()->id));
2181         if ($this->can_grade()) {
2182             $o .= $this->output->render(new assign_grading_summary($this->count_participants(0),
2183                                                             $this->get_instance()->submissiondrafts,
2184                                                             $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2185                                                             $this->is_any_submission_plugin_enabled(),
2186                                                             $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2187                                                             $this->get_instance()->duedate,
2188                                                             $this->get_course_module()->id,
2189                                                             $this->count_submissions_need_grading()
2190                                                             ));
2191         }
2192         $grade = $this->get_user_grade($USER->id, false);
2193         $submission = $this->get_user_submission($USER->id, false);
2195         if ($this->can_view_submission($USER->id)) {
2196             $o .= $this->view_student_summary($USER, true);
2197         }
2200         $o .= $this->view_footer();
2201         $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
2202         return $o;
2203     }
2205     /**
2206      * convert the final raw grade(s) in the  grading table for the gradebook
2207      *
2208      * @param stdClass $grade
2209      * @return array
2210      */
2211     private function convert_grade_for_gradebook(stdClass $grade) {
2212         $gradebookgrade = array();
2213         // trying to match those array keys in grade update function in gradelib.php
2214         // with keys in th database table assign_grades
2215         // starting around line 262
2216         if ($grade->grade >= 0) {
2217             $gradebookgrade['rawgrade'] = $grade->grade;
2218         }
2219         $gradebookgrade['userid'] = $grade->userid;
2220         $gradebookgrade['usermodified'] = $grade->grader;
2221         $gradebookgrade['datesubmitted'] = NULL;
2222         $gradebookgrade['dategraded'] = $grade->timemodified;
2223         if (isset($grade->feedbackformat)) {
2224             $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
2225         }
2226         if (isset($grade->feedbacktext)) {
2227             $gradebookgrade['feedback'] = $grade->feedbacktext;
2228         }
2230         return $gradebookgrade;
2231     }
2233     /**
2234      * convert submission details for the gradebook
2235      *
2236      * @param stdClass $submission
2237      * @return array
2238      */
2239     private function convert_submission_for_gradebook(stdClass $submission) {
2240         $gradebookgrade = array();
2243         $gradebookgrade['userid'] = $submission->userid;
2244         $gradebookgrade['usermodified'] = $submission->userid;
2245         $gradebookgrade['datesubmitted'] = $submission->timemodified;
2247         return $gradebookgrade;
2248     }
2250     /**
2251      * update grades in the gradebook
2252      *
2253      * @param mixed $submission stdClass|null
2254      * @param mixed $grade stdClass|null
2255      * @return bool
2256      */
2257     private function gradebook_item_update($submission=NULL, $grade=NULL) {
2259         if($submission != NULL){
2260             $gradebookgrade = $this->convert_submission_for_gradebook($submission);
2261         }else{
2262             $gradebookgrade = $this->convert_grade_for_gradebook($grade);
2263         }
2264         // Grading is disabled, return.
2265         if ($this->grading_disabled($gradebookgrade['userid'])) {
2266             return false;
2267         }
2268         $assign = clone $this->get_instance();
2269         $assign->cmidnumber = $this->get_course_module()->id;
2271         return assign_grade_item_update($assign, $gradebookgrade);
2272     }
2274     /**
2275      * update grades in the gradebook based on submission time
2276      *
2277      * @param stdClass $submission
2278      * @param bool $updatetime
2279      * @return bool
2280      */
2281     private function update_submission(stdClass $submission, $updatetime=true) {
2282         global $DB;
2284         if ($updatetime) {
2285             $submission->timemodified = time();
2286         }
2287         $result= $DB->update_record('assign_submission', $submission);
2288         if ($result) {
2289             $this->gradebook_item_update($submission);
2290         }
2291         return $result;
2292     }
2294     /**
2295      * Is this assignment open for submissions?
2296      *
2297      * Check the due date,
2298      * prevent late submissions,
2299      * has this person already submitted,
2300      * is the assignment locked?
2301      *
2302      * @return bool
2303      */
2304     private function submissions_open() {
2305         global $USER;
2307         $time = time();
2308         $dateopen = true;
2309         if ($this->get_instance()->preventlatesubmissions && $this->get_instance()->duedate) {
2310             $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $this->get_instance()->duedate);
2311         } else {
2312             $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
2313         }
2315         if (!$dateopen) {
2316             return false;
2317         }
2319         // now check if this user has already submitted etc.
2320         if (!is_enrolled($this->get_course_context(), $USER)) {
2321             return false;
2322         }
2323         if ($submission = $this->get_user_submission($USER->id, false)) {
2324             if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2325                 // drafts are tracked and the student has submitted the assignment
2326                 return false;
2327             }
2328         }
2329         if ($grade = $this->get_user_grade($USER->id, false)) {
2330             if ($grade->locked) {
2331                 return false;
2332             }
2333         }
2335         if ($this->grading_disabled($USER->id)) {
2336             return false;
2337         }
2339         return true;
2340     }
2342     /**
2343      * render the files in file area
2344      * @param string $component
2345      * @param string $area
2346      * @param int $submissionid
2347      * @return string
2348      */
2349     public function render_area_files($component, $area, $submissionid) {
2350         global $USER;
2352         if (!$submissionid) {
2353             $submission = $this->get_user_submission($USER->id,false);
2354             $submissionid = $submission->id;
2355         }
2357         $fs = get_file_storage();
2358         $browser = get_file_browser();
2359         $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
2360         return $this->output->assign_files($this->context, $submissionid, $area, $component);
2362     }
2364     /**
2365      * Returns a list of teachers that should be grading given submission
2366      *
2367      * @param int $userid
2368      * @return array
2369      */
2370     private function get_graders($userid) {
2371         //potential graders
2372         $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");
2374         $graders = array();
2375         if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) {   // Separate groups are being used
2376             if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) {  // Try to find all groups
2377                 foreach ($groups as $group) {
2378                     foreach ($potentialgraders as $grader) {
2379                         if ($grader->id == $userid) {
2380                             continue; // do not send self
2381                         }
2382                         if (groups_is_member($group->id, $grader->id)) {
2383                             $graders[$grader->id] = $grader;
2384                         }
2385                     }
2386                 }
2387             } else {
2388                 // user not in group, try to find graders without group
2389                 foreach ($potentialgraders as $grader) {
2390                     if ($grader->id == $userid) {
2391                         continue; // do not send self
2392                     }
2393                     if (!groups_has_membership($this->get_course_module(), $grader->id)) {
2394                         $graders[$grader->id] = $grader;
2395                     }
2396                 }
2397             }
2398         } else {
2399             foreach ($potentialgraders as $grader) {
2400                 if ($grader->id == $userid) {
2401                     continue; // do not send self
2402                 }
2403                 // must be enrolled
2404                 if (is_enrolled($this->get_course_context(), $grader->id)) {
2405                     $graders[$grader->id] = $grader;
2406                 }
2407             }
2408         }
2409         return $graders;
2410     }
2412     /**
2413      * Format a notification for plain text
2414      *
2415      * @param string $messagetype
2416      * @param stdClass $info
2417      * @param stdClass $course
2418      * @param stdClass $context
2419      * @param string $modulename
2420      * @param string $assignmentname
2421      */
2422     private static function format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname) {
2423         $posttext  = format_string($course->shortname, true, array('context' => $context->get_course_context())).' -> '.
2424                      $modulename.' -> '.
2425                      format_string($assignmentname, true, array('context' => $context))."\n";
2426         $posttext .= '---------------------------------------------------------------------'."\n";
2427         $posttext .= get_string($messagetype . 'text', "assign", $info)."\n";
2428         $posttext .= "\n---------------------------------------------------------------------\n";
2429         return $posttext;
2430     }
2432     /**
2433      * Format a notification for HTML
2434      *
2435      * @param string $messagetype
2436      * @param stdClass $info
2437      * @param stdClass $course
2438      * @param stdClass $context
2439      * @param string $modulename
2440      * @param stdClass $coursemodule
2441      * @param string $assignmentname
2442      * @param stdClass $info
2443      */
2444     private static function format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) {
2445         global $CFG;
2446         $posthtml  = '<p><font face="sans-serif">'.
2447                      '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.format_string($course->shortname, true, array('context' => $context->get_course_context())).'</a> ->'.
2448                      '<a href="'.$CFG->wwwroot.'/mod/assign/index.php?id='.$course->id.'">'.$modulename.'</a> ->'.
2449                      '<a href="'.$CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id.'">'.format_string($assignmentname, true, array('context' => $context)).'</a></font></p>';
2450         $posthtml .= '<hr /><font face="sans-serif">';
2451         $posthtml .= '<p>'.get_string($messagetype . 'html', 'assign', $info).'</p>';
2452         $posthtml .= '</font><hr />';
2453         return $posthtml;
2454     }
2456     /**
2457      * Message someone about something (static so it can be called from cron)
2458      *
2459      * @param stdClass $userfrom
2460      * @param stdClass $userto
2461      * @param string $messagetype
2462      * @param string $eventtype
2463      * @param int $updatetime
2464      * @param stdClass $coursemodule
2465      * @param stdClass $context
2466      * @param stdClass $course
2467      * @param string $modulename
2468      * @param string $assignmentname
2469      * @return void
2470      */
2471     public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
2472                                                         $updatetime, $coursemodule, $context, $course,
2473                                                         $modulename, $assignmentname) {
2474         global $CFG;
2476         $info = new stdClass();
2477         $info->username = fullname($userfrom, true);
2478         $info->assignment = format_string($assignmentname,true, array('context'=>$context));
2479         $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
2480         $info->timeupdated = strftime('%c',$updatetime);
2482         $postsubject = get_string($messagetype . 'small', 'assign', $info);
2483         $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
2484         $posthtml = ($userto->mailformat == 1) ? self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) : '';
2486         $eventdata = new stdClass();
2487         $eventdata->modulename       = 'assign';
2488         $eventdata->userfrom         = $userfrom;
2489         $eventdata->userto           = $userto;
2490         $eventdata->subject          = $postsubject;
2491         $eventdata->fullmessage      = $posttext;
2492         $eventdata->fullmessageformat = FORMAT_PLAIN;
2493         $eventdata->fullmessagehtml  = $posthtml;
2494         $eventdata->smallmessage     = $postsubject;
2496         $eventdata->name            = $eventtype;
2497         $eventdata->component       = 'mod_assign';
2498         $eventdata->notification    = 1;
2499         $eventdata->contexturl      = $info->url;
2500         $eventdata->contexturlname  = $info->assignment;
2502         message_send($eventdata);
2503     }
2505     /**
2506      * Message someone about something
2507      *
2508      * @param stdClass $userfrom
2509      * @param stdClass $userto
2510      * @param string $messagetype
2511      * @param string $eventtype
2512      * @param int $updatetime
2513      * @return void
2514      */
2515     public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
2516         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);
2517     }
2519     /**
2520      * Notify student upon successful submission
2521      *
2522      * @global moodle_database $DB
2523      * @param stdClass $submission
2524      * @return void
2525      */
2526     private function notify_student_submission_receipt(stdClass $submission) {
2527         global $DB;
2529         $adminconfig = $this->get_admin_config();
2530         if (!$adminconfig->submissionreceipts) {
2531             // No need to do anything
2532             return;
2533         }
2534         $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
2535         $this->send_notification($user, $user, 'submissionreceipt', 'assign_notification', $submission->timemodified);
2536     }
2538     /**
2539      * Send notifications to graders upon student submissions
2540      *
2541      * @global moodle_database $DB
2542      * @param stdClass $submission
2543      * @return void
2544      */
2545     private function notify_graders(stdClass $submission) {
2546         global $DB;
2548         $late = $this->get_instance()->duedate && ($this->get_instance()->duedate < time());
2550         if (!$this->get_instance()->sendnotifications && !($late && $this->get_instance()->sendlatenotifications)) {          // No need to do anything
2551             return;
2552         }
2554         $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
2555         if ($teachers = $this->get_graders($user->id)) {
2556             foreach ($teachers as $teacher) {
2557                 $this->send_notification($user, $teacher, 'gradersubmissionupdated', 'assign_notification', $submission->timemodified);
2558             }
2559         }
2560     }
2562     /**
2563      * assignment submission is processed before grading
2564      *
2565      * @return void
2566      */
2567     private function process_submit_for_grading() {
2568         global $USER;
2570         // Need submit permission to submit an assignment
2571         require_capability('mod/assign:submit', $this->context);
2572         require_sesskey();
2574         $submission = $this->get_user_submission($USER->id,true);
2575         if ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2576             // Give each submission plugin a chance to process the submission
2577             $plugins = $this->get_submission_plugins();
2578             foreach ($plugins as $plugin) {
2579                 $plugin->submit_for_grading();
2580             }
2582             $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2583             $this->update_submission($submission);
2584             $this->add_to_log('submit for grading', $this->format_submission_for_log($submission));
2585             $this->notify_graders($submission);
2586             $this->notify_student_submission_receipt($submission);
2587         }
2588     }
2590     /**
2591      * save quick grades
2592      *
2593      * @global moodle_database $DB
2594      * @return string The result of the save operation
2595      */
2596     private function process_save_quick_grades() {
2597         global $USER, $DB, $CFG;
2599         // Need grade permission
2600         require_capability('mod/assign:grade', $this->context);
2602         // make sure advanced grading is disabled
2603         $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2604         $controller = $gradingmanager->get_active_controller();
2605         if (!empty($controller)) {
2606             return get_string('errorquickgradingvsadvancedgrading', 'assign');
2607         }
2609         $users = array();
2610         // first check all the last modified values
2611         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2612         $participants = $this->list_participants($currentgroup, true);
2614         // gets a list of possible users and look for values based upon that.
2615         foreach ($participants as $userid => $unused) {
2616             $modified = optional_param('grademodified_' . $userid, -1, PARAM_INT);
2617             if ($modified >= 0) {
2618                 // gather the userid, updated grade and last modified value
2619                 $record = new stdClass();
2620                 $record->userid = $userid;
2621                 $record->grade = unformat_float(required_param('quickgrade_' . $record->userid, PARAM_TEXT));
2622                 $record->lastmodified = $modified;
2623                 $record->gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2624                 $users[$userid] = $record;
2625             }
2626         }
2627         if (empty($users)) {
2628             // Quick check to see whether we have any users to update and we don't
2629             return get_string('quickgradingchangessaved', 'assign'); // Technical lie
2630         }
2632         list($userids, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED);
2633         $params['assignment'] = $this->get_instance()->id;
2634         // check them all for currency
2635         $sql = 'SELECT u.id as userid, g.grade as grade, g.timemodified as lastmodified
2636                   FROM {user} u
2637              LEFT JOIN {assign_grades} g ON u.id = g.userid AND g.assignment = :assignment
2638                  WHERE u.id ' . $userids;
2639         $currentgrades = $DB->get_recordset_sql($sql, $params);
2641         $modifiedusers = array();
2642         foreach ($currentgrades as $current) {
2643             $modified = $users[(int)$current->userid];
2644             $grade = $this->get_user_grade($userid, false);
2646             // check to see if the outcomes were modified
2647             if ($CFG->enableoutcomes) {
2648                 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2649                     $oldoutcome = $outcome->grades[$modified->userid]->grade;
2650                     $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_FLOAT);
2651                     if ($oldoutcome != $newoutcome) {
2652                         // can't check modified time for outcomes because it is not reported
2653                         $modifiedusers[$modified->userid] = $modified;
2654                         continue;
2655                     }
2656                 }
2657             }
2659             // let plugins participate
2660             foreach ($this->feedbackplugins as $plugin) {
2661                 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2662                     if ($plugin->is_quickgrading_modified($modified->userid, $grade)) {
2663                         if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2664                             return get_string('errorrecordmodified', 'assign');
2665                         } else {
2666                             $modifiedusers[$modified->userid] = $modified;
2667                             continue;
2668                         }
2669                     }
2670                 }
2671             }
2674             if (($current->grade < 0 || $current->grade === NULL) &&
2675                 ($modified->grade < 0 || $modified->grade === NULL)) {
2676                 // different ways to indicate no grade
2677                 continue;
2678             }
2679             // Treat 0 and null as different values
2680             if ($current->grade !== null) {
2681                 $current->grade = floatval($current->grade);
2682             }
2683             if ($current->grade !== $modified->grade) {
2684                 // grade changed
2685                 if ($this->grading_disabled($modified->userid)) {
2686                     continue;
2687                 }
2688                 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2689                     // error - record has been modified since viewing the page
2690                     return get_string('errorrecordmodified', 'assign');
2691                 } else {
2692                     $modifiedusers[$modified->userid] = $modified;
2693                 }
2694             }
2696         }
2697         $currentgrades->close();
2699         $adminconfig = $this->get_admin_config();
2700         $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
2702         // ok - ready to process the updates
2703         foreach ($modifiedusers as $userid => $modified) {
2704             $grade = $this->get_user_grade($userid, true);
2705             $grade->grade= grade_floatval(unformat_float($modified->grade));
2706             $grade->grader= $USER->id;
2708             // save plugins data
2709             foreach ($this->feedbackplugins as $plugin) {
2710                 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2711                     $plugin->save_quickgrading_changes($userid, $grade);
2712                     if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
2713                         // This is the feedback plugin chose to push comments to the gradebook.
2714                         $grade->feedbacktext = $plugin->text_for_gradebook($grade);
2715                         $grade->feedbackformat = $plugin->format_for_gradebook($grade);
2716                     }
2717                 }
2718             }
2720             $this->update_grade($grade);
2722             // save outcomes
2723             if ($CFG->enableoutcomes) {
2724                 $data = array();
2725                 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2726                     $oldoutcome = $outcome->grades[$modified->userid]->grade;
2727                     $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_INT);
2728                     if ($oldoutcome != $newoutcome) {
2729                         $data[$outcomeid] = $newoutcome;
2730                     }
2731                 }
2732                 if (count($data) > 0) {
2733                     grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
2734                 }
2735             }
2737             $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
2738         }
2740         return get_string('quickgradingchangessaved', 'assign');
2741     }
2743     /**
2744      * save grading options
2745      *
2746      * @return void
2747      */
2748     private function process_save_grading_options() {
2749         global $USER, $CFG;
2751         // Include grading options form
2752         require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2754         // Need submit permission to submit an assignment
2755         require_capability('mod/assign:grade', $this->context);
2757         $mform = new mod_assign_grading_options_form(null, array('cm'=>$this->get_course_module()->id,
2758                                                                  'contextid'=>$this->context->id,
2759                                                                  'userid'=>$USER->id,
2760                                                                  'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2761                                                                  'showquickgrading'=>false));
2762         if ($formdata = $mform->get_data()) {
2763             set_user_preference('assign_perpage', $formdata->perpage);
2764             set_user_preference('assign_filter', $formdata->filter);
2765         }
2766     }
2768    /**
2769     * Take a grade object and print a short summary for the log file.
2770     * The size limit for the log file is 255 characters, so be careful not
2771     * to include too much information.
2772     *
2773     * @param stdClass $grade
2774     * @return string
2775     */
2776     private function format_grade_for_log(stdClass $grade) {
2777         global $DB;
2779         $user = $DB->get_record('user', array('id' => $grade->userid), '*', MUST_EXIST);
2781         $info = get_string('gradestudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
2782         if ($grade->grade != '') {
2783             $info .= get_string('grade') . ': ' . $this->display_grade($grade->grade, false) . '. ';
2784         } else {
2785             $info .= get_string('nograde', 'assign');
2786         }
2787         if ($grade->locked) {
2788             $info .= get_string('submissionslocked', 'assign') . '. ';
2789         }
2790         return $info;
2791     }
2793     /**
2794      * Take a submission object and print a short summary for the log file.
2795      * The size limit for the log file is 255 characters, so be careful not
2796      * to include too much information.
2797      *
2798      * @param stdClass $submission
2799      * @return string
2800      */
2801     private function format_submission_for_log(stdClass $submission) {
2802         $info = '';
2803         $info .= get_string('submissionstatus', 'assign') . ': ' . get_string('submissionstatus_' . $submission->status, 'assign') . '. <br>';
2804         // format_for_log here iterating every single log INFO  from either submission or grade in every assignment plugin
2806         foreach ($this->submissionplugins as $plugin) {
2807             if ($plugin->is_enabled() && $plugin->is_visible()) {
2810                 $info .= "<br>" . $plugin->format_for_log($submission);
2811             }
2812         }
2815         return $info;
2816     }
2818     /**
2819      * save assignment submission
2820      *
2821      * @param  moodleform $mform
2822      * @return bool
2823      */
2824     private function process_save_submission(&$mform) {
2825         global $USER, $CFG;
2827         // Include submission form
2828         require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2830         // Need submit permission to submit an assignment
2831         require_capability('mod/assign:submit', $this->context);
2832         require_sesskey();
2834         $data = new stdClass();
2835         $mform = new mod_assign_submission_form(null, array($this, $data));
2836         if ($mform->is_cancelled()) {
2837             return true;
2838         }
2839         if ($data = $mform->get_data()) {
2840             $submission = $this->get_user_submission($USER->id, true); //create the submission if needed & its id
2841             $grade = $this->get_user_grade($USER->id, false); // get the grade to check if it is locked
2842             if ($grade && $grade->locked) {
2843                 print_error('submissionslocked', 'assign');
2844                 return true;
2845             }
2848             foreach ($this->submissionplugins as $plugin) {
2849                 if ($plugin->is_enabled()) {
2850                     if (!$plugin->save($submission, $data)) {
2851                         print_error($plugin->get_error());
2852                     }
2853                 }
2854             }
2856             $this->update_submission($submission);
2858             // Logging
2859             $this->add_to_log('submit', $this->format_submission_for_log($submission));
2861             if (!$this->get_instance()->submissiondrafts) {
2862                 $this->notify_student_submission_receipt($submission);
2863                 $this->notify_graders($submission);
2864             }
2865             return true;
2866         }
2867         return false;
2868     }
2871     /**
2872      * Determine if this users grade is locked or overridden
2873      *
2874      * @param int $userid - The student userid
2875      * @return bool $gradingdisabled
2876      */
2877     public function grading_disabled($userid) {
2878         global $CFG;
2880         $gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2881         if (!$gradinginfo) {
2882             return false;
2883         }
2885         if (!isset($gradinginfo->items[0]->grades[$userid])) {
2886             return false;
2887         }
2888         $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
2889         return $gradingdisabled;
2890     }
2893     /**
2894      * Get an instance of a grading form if advanced grading is enabled
2895      * This is specific to the assignment, marker and student
2896      *
2897      * @param int $userid - The student userid
2898      * @param bool $gradingdisabled
2899      * @return mixed gradingform_instance|null $gradinginstance
2900      */
2901     private function get_grading_instance($userid, $gradingdisabled) {
2902         global $CFG, $USER;
2904         $grade = $this->get_user_grade($userid, false);
2905         $grademenu = make_grades_menu($this->get_instance()->grade);
2907         $advancedgradingwarning = false;
2908         $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2909         $gradinginstance = null;
2910         if ($gradingmethod = $gradingmanager->get_active_method()) {
2911             $controller = $gradingmanager->get_controller($gradingmethod);
2912             if ($controller->is_form_available()) {
2913                 $itemid = null;
2914                 if ($grade) {
2915                     $itemid = $grade->id;
2916                 }
2917                 if ($gradingdisabled && $itemid) {
2918                     $gradinginstance = ($controller->get_current_instance($USER->id, $itemid));
2919                 } else if (!$gradingdisabled) {
2920                     $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
2921                     $gradinginstance = ($controller->get_or_create_instance($instanceid, $USER->id, $itemid));
2922                 }
2923             } else {
2924                 $advancedgradingwarning = $controller->form_unavailable_notification();
2925             }
2926         }
2927         if ($gradinginstance) {
2928             $gradinginstance->get_controller()->set_grade_range($grademenu);
2929         }
2930         return $gradinginstance;
2931     }
2933     /**
2934      * add elements to grade form
2935      *
2936      * @param MoodleQuickForm $mform
2937      * @param stdClass $data
2938      * @param array $params
2939      * @return void
2940      */
2941     public function add_grade_form_elements(MoodleQuickForm $mform, stdClass $data, $params) {
2942         global $USER, $CFG;
2943         $settings = $this->get_instance();
2945         $rownum = $params['rownum'];
2946         $last = $params['last'];
2947         $useridlist = $params['useridlist'];
2948         $userid = $useridlist[$rownum];
2949         $grade = $this->get_user_grade($userid, false);
2951         // add advanced grading
2952         $gradingdisabled = $this->grading_disabled($userid);
2953         $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
2955         if ($gradinginstance) {
2956             $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2957             if ($gradingdisabled) {
2958                 $gradingelement->freeze();
2959             } else {
2960                 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2961             }
2962         } else {
2963             // use simple direct grading
2964             if ($this->get_instance()->grade > 0) {
2965                 $gradingelement = $mform->addElement('text', 'grade', get_string('gradeoutof', 'assign',$this->get_instance()->grade));
2966                 $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
2967                 $mform->setType('grade', PARAM_TEXT);
2968                 if ($gradingdisabled) {
2969                     $gradingelement->freeze();
2970                 }
2971             } else {
2972                 $grademenu = make_grades_menu($this->get_instance()->grade);
2973                 if (count($grademenu) > 0) {
2974                     $gradingelement = $mform->addElement('select', 'grade', get_string('grade').':', $grademenu);
2975                     $mform->setType('grade', PARAM_INT);
2976                     if ($gradingdisabled) {
2977                         $gradingelement->freeze();
2978                     }
2979                 }
2980             }
2981         }
2983         $gradinginfo = grade_get_grades($this->get_course()->id,
2984                                         'mod',
2985                                         'assign',
2986                                         $this->get_instance()->id,
2987                                         $userid);
2988         if (!empty($CFG->enableoutcomes)) {
2989             foreach($gradinginfo->outcomes as $index=>$outcome) {
2990                 $options = make_grades_menu(-$outcome->scaleid);
2991                 if ($outcome->grades[$userid]->locked) {
2992                     $options[0] = get_string('nooutcome', 'grades');
2993                     $mform->addElement('static', 'outcome_'.$index.'['.$userid.']', $outcome->name.':',
2994                             $options[$outcome->grades[$userid]->grade]);
2995                 } else {
2996                     $options[''] = get_string('nooutcome', 'grades');
2997                     $attributes = array('id' => 'menuoutcome_'.$index );
2998                     $mform->addElement('select', 'outcome_'.$index.'['.$userid.']', $outcome->name.':', $options, $attributes );
2999                     $mform->setType('outcome_'.$index.'['.$userid.']', PARAM_INT);
3000                     $mform->setDefault('outcome_'.$index.'['.$userid.']', $outcome->grades[$userid]->grade );
3001                 }
3002             }
3003         }
3005         if (has_all_capabilities(array('gradereport/grader:view', 'moodle/grade:viewall'), $this->get_course_context())) {
3006             $gradestring = $this->output->action_link(new moodle_url('/grade/report/grader/index.php',
3007                                                               array('id'=>$this->get_course()->id)),
3008                                                 $gradinginfo->items[0]->grades[$userid]->str_grade);
3009         } else {
3010             $gradestring = $gradinginfo->items[0]->grades[$userid]->str_grade;
3011         }
3012         $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assign').':', $gradestring);
3015         $mform->addElement('static', 'progress', '', get_string('gradingstudentprogress', 'assign', array('index'=>$rownum+1, 'count'=>count($useridlist))));
3017         // Let feedback plugins add elements to the grading form.
3018         $this->add_plugin_grade_elements($grade, $mform, $data, $userid);
3020         // hidden params
3021         $mform->addElement('hidden', 'id', $this->get_course_module()->id);
3022         $mform->setType('id', PARAM_INT);
3023         $mform->addElement('hidden', 'rownum', $rownum);
3024         $mform->setType('rownum', PARAM_INT);
3025         $mform->setConstant('rownum', $rownum);
3026         $mform->addElement('hidden', 'useridlist', implode(',', $useridlist));
3027         $mform->setType('useridlist', PARAM_TEXT);
3028         $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT));
3029         $mform->setType('ajax', PARAM_INT);
3031         $mform->addElement('hidden', 'action', 'submitgrade');
3032         $mform->setType('action', PARAM_ALPHA);
3035         $buttonarray=array();
3036         $buttonarray[] = $mform->createElement('submit', 'savegrade', get_string('savechanges', 'assign'));
3037         if (!$last){
3038             $buttonarray[] = $mform->createElement('submit', 'saveandshownext', get_string('savenext','assign'));
3039         }
3040         $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
3041         $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
3042         $mform->closeHeaderBefore('buttonar');
3043         $buttonarray=array();
3045         if ($rownum > 0) {
3046             $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', get_string('previous','assign'));
3047         }
3049         if (!$last){
3050             $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', get_string('nosavebutnext', 'assign'));
3051         }
3052         $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
3053     }
3056     /**
3057      * add elements in submission plugin form
3058      *
3059      * @param mixed $submission stdClass|null
3060      * @param MoodleQuickForm $mform
3061      * @param stdClass $data
3062      * @param int $userid The current userid (same as $USER->id)
3063      * @return void
3064      */
3065     private function add_plugin_submission_elements($submission, MoodleQuickForm $mform, stdClass $data, $userid) {
3066         foreach ($this->submissionplugins as $plugin) {
3067             if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
3068                 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
3069                 if (!$plugin->get_form_elements_for_user($submission, $mform, $data, $userid)) {
3070                     $mform->removeElement('header_' . $plugin->get_type());
3071                 }
3072             }
3073         }
3074     }
3076     /**
3077      * check if feedback plugins installed are enabled
3078      *
3079      * @return bool
3080      */
3081     public function is_any_feedback_plugin_enabled() {
3082         if (!isset($this->cache['any_feedback_plugin_enabled'])) {
3083             $this->cache['any_feedback_plugin_enabled'] = false;
3084             foreach ($this->feedbackplugins as $plugin) {
3085                 if ($plugin->is_enabled() && $plugin->is_visible()) {
3086                     $this->cache['any_feedback_plugin_enabled'] = true;
3087                     break;
3088                 }
3089             }
3090         }
3092         return $this->cache['any_feedback_plugin_enabled'];
3094     }
3096     /**
3097      * check if submission plugins installed are enabled
3098      *
3099      * @return bool
3100      */
3101     public function is_any_submission_plugin_enabled() {
3102         if (!isset($this->cache['any_submission_plugin_enabled'])) {
3103             $this->cache['any_submission_plugin_enabled'] = false;
3104             foreach ($this->submissionplugins as $plugin) {
3105                 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
3106                     $this->cache['any_submission_plugin_enabled'] = true;
3107                     break;
3108                 }
3109             }
3110         }
3112         return $this->cache['any_submission_plugin_enabled'];
3114     }
3116     /**
3117      * add elements to submission form
3118      * @param MoodleQuickForm $mform
3119      * @param stdClass $data
3120      * @return void
3121      */
3122     public function add_submission_form_elements(MoodleQuickForm $mform, stdClass $data) {
3123         global $USER;
3125         // online text submissions
3127         $submission = $this->get_user_submission($USER->id, false);
3129         $this->add_plugin_submission_elements($submission, $mform, $data, $USER->id);
3131         // hidden params
3132         $mform->addElement('hidden', 'id', $this->get_course_module()->id);
3133         $mform->setType('id', PARAM_INT);
3135         $mform->addElement('hidden', 'action', 'savesubmission');
3136         $mform->setType('action', PARAM_TEXT);
3137         // buttons
3139     }
3141     /**
3142      * revert to draft
3143      * Uses url parameter userid
3144      *
3145      * @param int $userid
3146      * @return void
3147      */
3148     private function process_revert_to_draft($userid = 0) {
3149         global $USER, $DB;
3151         // Need grade permission
3152         require_capability('mod/assign:grade', $this->context);
3153         require_sesskey();
3155         if (!$userid) {
3156             $userid = required_param('userid', PARAM_INT);
3157         }
3159         $submission = $this->get_user_submission($userid, false);
3160         if (!$submission) {
3161             return;
3162         }
3163         $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3164         $this->update_submission($submission, false);
3166         // update the modified time on the grade (grader modified)
3167         $grade = $this->get_user_grade($userid, true);
3168         $this->update_grade($grade);
3170         $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3172         $this->add_to_log('revert submission to draft', get_string('reverttodraftforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3174     }
3176     /**
3177      * lock  the process
3178      * Uses url parameter userid
3179      * @param int $userid
3180      * @return void
3181      */
3182     private function process_lock($userid = 0) {
3183         global $USER, $DB;
3185         // Need grade permission
3186         require_capability('mod/assign:grade', $this->context);
3187         require_sesskey();
3189         if (!$userid) {
3190             $userid = required_param('userid', PARAM_INT);
3191         }
3193         $grade = $this->get_user_grade($userid, true);
3194         $grade->locked = 1;
3195         $grade->grader = $USER->id;
3196         $this->update_grade($grade);
3198         $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3200         $this->add_to_log('lock submission', get_string('locksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3201     }
3203     /**
3204      * unlock the process
3205      *
3206      * @param int $userid
3207      * @return void
3208      */
3209     private function process_unlock($userid = 0) {
3210         global $USER, $DB;
3212         // Need grade permission
3213         require_capability('mod/assign:grade', $this->context);
3214         require_sesskey();
3216         if (!$userid) {
3217             $userid = required_param('userid', PARAM_INT);
3218         }
3220         $grade = $this->get_user_grade($userid, true);
3221         $grade->locked = 0;
3222         $grade->grader = $USER->id;
3223         $this->update_grade($grade);
3225         $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3227         $this->add_to_log('unlock submission', get_string('unlocksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3228     }
3230     /**
3231      * save outcomes submitted from grading form
3232      *
3233      * @param int $userid
3234      * @param stdClass $formdata
3235      */
3236     private function process_outcomes($userid, $formdata) {
3237         global $CFG, $USER;
3239         if (empty($CFG->enableoutcomes)) {
3240             return;
3241         }
3242         if ($this->grading_disabled($userid)) {
3243             return;
3244         }
3246         require_once($CFG->libdir.'/gradelib.php');
3248         $data = array();
3249         $gradinginfo = grade_get_grades($this->get_course()->id,
3250                                         'mod',
3251                                         'assign',
3252                                         $this->get_instance()->id,
3253                                         $userid);
3255         if (!empty($gradinginfo->outcomes)) {
3256             foreach($gradinginfo->outcomes as $index=>$oldoutcome) {
3257                 $name = 'outcome_'.$index;
3258                 if (isset($formdata->{$name}[$userid]) and $oldoutcome->grades[$userid]->grade != $formdata->{$name}[$userid]) {
3259                     $data[$index] = $formdata->{$name}[$userid];
3260                 }
3261             }
3262         }
3263         if (count($data) > 0) {
3264             grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
3265         }
3267     }
3270     /**
3271      * save grade
3272      *
3273      * @param  moodleform $mform
3274      * @return bool - was the grade saved
3275      */
3276     private function process_save_grade(&$mform) {
3277         global $USER, $DB, $CFG;
3278         // Include grade form
3279         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3281         // Need submit permission to submit an assignment
3282         require_capability('mod/assign:grade', $this->context);
3283         require_sesskey();
3285         $rownum = required_param('rownum', PARAM_INT);
3286         $useridlist = optional_param('useridlist', '', PARAM_TEXT);
3287         if ($useridlist) {
3288             $useridlist = explode(',', $useridlist);
3289         } else {
3290             $useridlist = $this->get_grading_userid_list();
3291         }
3292         $last = false;
3293         $userid = $useridlist[$rownum];
3294         if ($rownum == count($useridlist) - 1) {
3295             $last = true;
3296         }
3298         $data = new stdClass();
3299         $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>false)), 'post', '', array('class'=>'gradeform'));
3301         if ($formdata = $mform->get_data()) {
3302             $grade = $this->get_user_grade($userid, true);
3303             $gradingdisabled = $this->grading_disabled($userid);
3304             $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
3305             if (!$gradingdisabled) {
3306                 if ($gradinginstance) {
3307                     $grade->grade = $gradinginstance->submit_and_get_grade($formdata->advancedgrading, $grade->id);
3308                 } else {
3309                     // handle the case when grade is set to No Grade
3310                     if (isset($formdata->grade)) {
3311                         $grade->grade = grade_floatval(unformat_float($formdata->grade));
3312                     }
3313                 }
3314             }
3315             $grade->grader= $USER->id;
3317             $adminconfig = $this->get_admin_config();
3318             $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
3320             // call save in plugins
3321             foreach ($this->feedbackplugins as $plugin) {
3322                 if ($plugin->is_enabled() && $plugin->is_visible()) {
3323                     if (!$plugin->save($grade, $formdata)) {
3324                         $result = false;
3325                         print_error($plugin->get_error());
3326                     }
3327                     if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
3328                         // this is the feedback plugin chose to push comments to the gradebook