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