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