c47d036f048ecb20fd549f6f401e16a2a9c850d8
[moodle.git] / mod / assign / feedback / offline / 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 library class for file feedback plugin
19  *
20  *
21  * @package   assignfeedback_offline
22  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
23  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 require_once($CFG->dirroot.'/grade/grading/lib.php');
30 /**
31  * library class for file feedback plugin extending feedback plugin base class
32  *
33  * @package   assignfeedback_offline
34  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
35  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36  */
37 class assign_feedback_offline extends assign_feedback_plugin {
39     /** @var boolean|null $enabledcache Cached lookup of the is_enabled function */
40     private $enabledcache = null;
42     /**
43      * Get the name of the file feedback plugin
44      * @return string
45      */
46     public function get_name() {
47         return get_string('pluginname', 'assignfeedback_offline');
48     }
50     /**
51      * Get form elements for grading form
52      *
53      * @param stdClass $grade
54      * @param MoodleQuickForm $mform
55      * @param stdClass $data
56      * @return bool true if elements were added to the form
57      */
58     public function get_form_elements($grade, MoodleQuickForm $mform, stdClass $data) {
59         return false;
60     }
62     /**
63      * Return true if there are no feedback files
64      * @param stdClass $grade
65      */
66     public function is_empty(stdClass $grade) {
67         return true;
68     }
70     /**
71      * Loop through uploaded grades and update the grades for this assignment
72      *
73      * @param int $draftid - The unique draft item id for this import
74      * @param int $importid - The unique import ID for this csv import operation
75      * @param bool $ignoremodified - Ignore the last modified date when checking fields
76      * @return string - The html response
77      */
78     public function process_import_grades($draftid, $importid, $ignoremodified) {
79         global $USER, $DB;
81         require_sesskey();
82         require_capability('mod/assign:grade', $this->assignment->get_context());
84         $gradeimporter = new assignfeedback_offline_grade_importer($importid, $this->assignment);
86         $context = context_user::instance($USER->id);
87         $fs = get_file_storage();
88         if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
89             redirect(new moodle_url('view.php',
90                                 array('id'=>$this->assignment->get_course_module()->id,
91                                       'action'=>'grading')));
92             return;
93         }
94         $file = reset($files);
96         $csvdata = $file->get_content();
98         if ($csvdata) {
99             $gradeimporter->parsecsv($csvdata);
100         }
101         if (!$gradeimporter->init()) {
102             $thisurl = new moodle_url('/mod/assign/view.php', array('action'=>'viewpluginpage',
103                                                                      'pluginsubtype'=>'assignfeedback',
104                                                                      'plugin'=>'offline',
105                                                                      'pluginaction'=>'uploadgrades',
106                                                                      'id'=>$assignment->get_course_module()->id));
107             print_error('invalidgradeimport', 'assignfeedback_offline', $thisurl);
108             return;
109         }
110         // Does this assignment use a scale?
111         $scaleoptions = null;
112         if ($this->assignment->get_instance()->grade < 0) {
113             if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->get_instance()->grade)))) {
114                 $scaleoptions = make_menu_from_list($scale->scale);
115             }
116         }
117         // We may need to upgrade the gradebook comments after this update.
118         $adminconfig = $this->assignment->get_admin_config();
119         $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
121         $updatecount = 0;
122         while ($record = $gradeimporter->next()) {
123             $user = $record->user;
124             $modified = $record->modified;
125             $userdesc = fullname($user);
126             $usergrade = $this->assignment->get_user_grade($user->id, false);
128             if (!empty($scaleoptions)) {
129                 // This is a scale - we need to convert any grades to indexes in the scale.
130                 $scaleindex = array_search($record->grade, $scaleoptions);
131                 if ($scaleindex !== false) {
132                     $record->grade = $scaleindex;
133                 } else {
134                     $record->grade = '';
135                 }
136             } else {
137                 $record->grade = unformat_float($record->grade);
138             }
140             // Note: Do not count the seconds when comparing modified dates.
141             $skip = false;
142             $stalemodificationdate = ($usergrade && $usergrade->timemodified > ($modified + 60));
144             if ($usergrade && $usergrade->grade == $record->grade) {
145                 // Skip - grade not modified.
146                 $skip = true;
147             } else if (!isset($record->grade) || $record->grade === '' || $record->grade < 0) {
148                 // Skip - grade has no value.
149                 $skip = true;
150             } else if (!$ignoremodified && $stalemodificationdate) {
151                 // Skip - grade has been modified.
152                 $skip = true;
153             } else if ($this->assignment->grading_disabled($record->user->id)) {
154                 // Skip grade is locked.
155                 $skip = true;
156             } else if (($this->assignment->get_instance()->grade > -1) &&
157                       (($record->grade < 0) || ($record->grade > $this->assignment->get_instance()->grade))) {
158                 // Out of range.
159                 $skip = true;
160             }
162             if (!$skip) {
163                 $grade = $this->assignment->get_user_grade($record->user->id, true);
165                 $grade->grade = $record->grade;
166                 $grade->grader = $USER->id;
167                 if ($this->assignment->update_grade($grade)) {
168                     $this->assignment->notify_grade_modified($grade);
169                     $this->assignment->add_to_log('grade submission', $this->assignment->format_grade_for_log($grade));
170                     $updatecount += 1;
171                 }
172             }
174             if ($ignoremodified || !$stalemodificationdate) {
175                 foreach ($record->feedback as $feedback) {
176                     $plugin = $feedback['plugin'];
177                     $field = $feedback['field'];
178                     $newvalue = $feedback['value'];
179                     $description = $feedback['description'];
180                     $oldvalue = '';
181                     if ($usergrade) {
182                         $oldvalue = $plugin->get_editor_text($field, $usergrade->id);
183                         if (empty($oldvalue)) {
184                             $oldvalue = '';
185                         }
186                     }
187                     if ($newvalue != $oldvalue) {
188                         $updatecount += 1;
189                         $grade = $this->assignment->get_user_grade($record->user->id, true);
190                         $this->assignment->notify_grade_modified($grade);
191                         if ($plugin->set_editor_text($field, $newvalue, $grade->id)) {
192                             $logdesc = get_string('feedbackupdate', 'assignfeedback_offline',
193                                                   array('field'=>$description,
194                                                         'student'=>$userdesc,
195                                                         'text'=>$newvalue));
197                             $this->assignment->add_to_log('save grading feedback', $logdesc);
198                         }
200                         // If this is the gradebook comments plugin - post an update to the gradebook.
201                         if (($plugin->get_subtype() . '_' . $plugin->get_type()) == $gradebookplugin) {
202                             $grade->feedbacktext = $plugin->text_for_gradebook($grade);
203                             $grade->feedbackformat = $plugin->format_for_gradebook($grade);
204                             $this->assignment->update_grade($grade);
205                         }
206                     }
207                 }
208             }
209         }
210         $gradeimporter->close(true);
212         $renderer = $this->assignment->get_renderer();
213         $o = '';
215         $o .= $renderer->render(new assign_header($this->assignment->get_instance(),
216                                                   $this->assignment->get_context(),
217                                                   false,
218                                                   $this->assignment->get_course_module()->id,
219                                                   get_string('importgrades', 'assignfeedback_offline')));
220         $o .= $renderer->box(get_string('updatedgrades', 'assignfeedback_offline', $updatecount));
221         $url = new moodle_url('view.php',
222                               array('id'=>$this->assignment->get_course_module()->id,
223                                     'action'=>'grading'));
224         $o .= $renderer->continue_button($url);
225         $o .= $renderer->render_footer();
226         return $o;
227     }
229     /**
230      * Display upload grades form
231      *
232      * @return string The response html
233      */
234     public function upload_grades() {
235         global $CFG, $USER;
237         require_capability('mod/assign:grade', $this->assignment->get_context());
238         require_once($CFG->dirroot . '/mod/assign/feedback/offline/uploadgradesform.php');
239         require_once($CFG->dirroot . '/mod/assign/feedback/offline/importgradesform.php');
240         require_once($CFG->dirroot . '/mod/assign/feedback/offline/importgradeslib.php');
241         require_once($CFG->libdir . '/csvlib.class.php');
243         $mform = new assignfeedback_offline_upload_grades_form(null,
244                                                               array('context'=>$this->assignment->get_context(),
245                                                                     'cm'=>$this->assignment->get_course_module()->id));
247         $o = '';
249         $confirm = optional_param('confirm', 0, PARAM_BOOL);
250         $renderer = $this->assignment->get_renderer();
252         if ($mform->is_cancelled()) {
253             redirect(new moodle_url('view.php',
254                                     array('id'=>$this->assignment->get_course_module()->id,
255                                           'action'=>'grading')));
256             return;
257         } else if (($data = $mform->get_data()) &&
258                    ($csvdata = $mform->get_file_content('gradesfile'))) {
260             $importid = csv_import_reader::get_new_iid('assignfeedback_offline');
261             $gradeimporter = new assignfeedback_offline_grade_importer($importid, $this->assignment);
262             // File exists and was valid.
263             $ignoremodified = !empty($data->ignoremodified);
265             $draftid = $data->gradesfile;
267             // Preview import.
269             $mform = new assignfeedback_offline_import_grades_form(null, array('assignment'=>$this->assignment,
270                                                                        'csvdata'=>$csvdata,
271                                                                        'ignoremodified'=>$ignoremodified,
272                                                                        'gradeimporter'=>$gradeimporter,
273                                                                        'draftid'=>$draftid));
275             $o .= $renderer->render(new assign_header($this->assignment->get_instance(),
276                                                             $this->assignment->get_context(),
277                                                             false,
278                                                             $this->assignment->get_course_module()->id,
279                                                             get_string('confirmimport', 'assignfeedback_offline')));
280             $o .= $renderer->render(new assign_form('confirmimport', $mform));
281             $o .= $renderer->render_footer();
282         } else if ($confirm) {
284             $importid = optional_param('importid', 0, PARAM_INT);
285             $draftid = optional_param('draftid', 0, PARAM_INT);
286             $ignoremodified = optional_param('ignoremodified', 0, PARAM_BOOL);
287             $gradeimporter = new assignfeedback_offline_grade_importer($importid, $this->assignment);
288             $mform = new assignfeedback_offline_import_grades_form(null, array('assignment'=>$this->assignment,
289                                                                        'csvdata'=>'',
290                                                                        'ignoremodified'=>$ignoremodified,
291                                                                        'gradeimporter'=>$gradeimporter,
292                                                                        'draftid'=>$draftid));
293             if ($mform->is_cancelled()) {
294                 redirect(new moodle_url('view.php',
295                                         array('id'=>$this->assignment->get_course_module()->id,
296                                               'action'=>'grading')));
297                 return;
298             }
300             $o .= $this->process_import_grades($draftid, $importid, $ignoremodified);
301         } else {
303             $o .= $renderer->render(new assign_header($this->assignment->get_instance(),
304                                                             $this->assignment->get_context(),
305                                                             false,
306                                                             $this->assignment->get_course_module()->id,
307                                                             get_string('uploadgrades', 'assignfeedback_offline')));
308             $o .= $renderer->render(new assign_form('batchuploadfiles', $mform));
309             $o .= $renderer->render_footer();
310         }
312         return $o;
313     }
315     /**
316      * Download a marking worksheet
317      *
318      * @return string The response html
319      */
320     public function download_grades() {
321         global $CFG;
323         require_capability('mod/assign:grade', $this->assignment->get_context());
324         require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
326         $groupmode = groups_get_activity_groupmode($this->assignment->get_course_module());
327         // All users.
328         $groupid = 0;
329         $groupname = '';
330         if ($groupmode) {
331             $groupid = groups_get_activity_group($this->assignment->get_course_module(), true);
332             $groupname = groups_get_group_name($groupid) . '-';
333         }
334         $filename = clean_filename(get_string('offlinegradingworksheet', 'assignfeedback_offline') . '-' .
335                                    $this->assignment->get_course()->shortname . '-' .
336                                    $this->assignment->get_instance()->name . '-' .
337                                    $groupname .
338                                    $this->assignment->get_course_module()->id);
340         $table = new assign_grading_table($this->assignment, 0, '', 0, false, $filename);
342         $table->out(0, false);
343         return;
344     }
346     /**
347      * Print a sub page in this plugin
348      *
349      * @param string $action - The plugin action
350      * @return string The response html
351      */
352     public function view_page($action) {
353         if ($action == 'downloadgrades') {
354             return $this->download_grades();
355         } else if ($action == 'uploadgrades') {
356             return $this->upload_grades();
357         }
359         return '';
360     }
362     /**
363      * Return a list of the grading actions performed by this plugin
364      * This plugin supports upload zip
365      *
366      * @return array The list of grading actions
367      */
368     public function get_grading_actions() {
369         return array('uploadgrades'=>get_string('uploadgrades', 'assignfeedback_offline'),
370                     'downloadgrades'=>get_string('downloadgrades', 'assignfeedback_offline'));
371     }
373     /**
374      * Override the default is_enabled to disable this plugin if advanced grading is active
375      *
376      * @return bool
377      */
378     public function is_enabled() {
379         if ($this->enabledcache === null) {
380             $gradingmanager = get_grading_manager($this->assignment->get_context(), 'mod_assign', 'submissions');
381             $controller = $gradingmanager->get_active_controller();
382             $active = !empty($controller);
384             if ($active) {
385                 $enabledcache = false;
386             } else {
387                 $enabledcache = parent::is_enabled();
388             }
389         }
390         return $this->enabledcache;
391     }
393     /**
394      * Do not show this plugin in the grading table or on the front page
395      *
396      * @return bool
397      */
398     public function has_user_summary() {
399         return false;
400     }