MDL-54061 mod_assign: Added encoding and separator to upload form.
[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      * This plugin does not save through the normal interface so this returns false.
72      *
73      * @param stdClass $grade The grade.
74      * @param stdClass $data Form data from the feedback form.
75      * @return boolean - False
76      */
77     public function is_feedback_modified(stdClass $grade, stdClass $data) {
78         return false;
79     }
81     /**
82      * Loop through uploaded grades and update the grades for this assignment
83      *
84      * @param int $draftid - The unique draft item id for this import
85      * @param int $importid - The unique import ID for this csv import operation
86      * @param bool $ignoremodified - Ignore the last modified date when checking fields
87      * @param string $encoding - Encoding of the file being processed.
88      * @param string $separator - The character used to separate the information.
89      * @return string - The html response
90      */
91     public function process_import_grades($draftid, $importid, $ignoremodified, $encoding = 'utf-8', $separator = 'comma') {
92         global $USER, $DB;
94         require_sesskey();
95         require_capability('mod/assign:grade', $this->assignment->get_context());
97         $gradeimporter = new assignfeedback_offline_grade_importer($importid, $this->assignment, $encoding, $separator);
99         $context = context_user::instance($USER->id);
100         $fs = get_file_storage();
101         if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
102             redirect(new moodle_url('view.php',
103                                 array('id'=>$this->assignment->get_course_module()->id,
104                                       'action'=>'grading')));
105             return;
106         }
107         $file = reset($files);
109         $csvdata = $file->get_content();
111         if ($csvdata) {
112             $gradeimporter->parsecsv($csvdata);
113         }
114         if (!$gradeimporter->init()) {
115             $thisurl = new moodle_url('/mod/assign/view.php', array('action'=>'viewpluginpage',
116                                                                      'pluginsubtype'=>'assignfeedback',
117                                                                      'plugin'=>'offline',
118                                                                      'pluginaction'=>'uploadgrades',
119                                                                      'id' => $this->assignment->get_course_module()->id));
120             print_error('invalidgradeimport', 'assignfeedback_offline', $thisurl);
121             return;
122         }
123         // Does this assignment use a scale?
124         $scaleoptions = null;
125         if ($this->assignment->get_instance()->grade < 0) {
126             if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->get_instance()->grade)))) {
127                 $scaleoptions = make_menu_from_list($scale->scale);
128             }
129         }
130         // We may need to upgrade the gradebook comments after this update.
131         $adminconfig = $this->assignment->get_admin_config();
132         $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
134         $updatecount = 0;
135         while ($record = $gradeimporter->next()) {
136             $user = $record->user;
137             $modified = $record->modified;
138             $userdesc = fullname($user);
139             $usergrade = $this->assignment->get_user_grade($user->id, false);
141             if (!empty($scaleoptions)) {
142                 // This is a scale - we need to convert any grades to indexes in the scale.
143                 $scaleindex = array_search($record->grade, $scaleoptions);
144                 if ($scaleindex !== false) {
145                     $record->grade = $scaleindex;
146                 } else {
147                     $record->grade = '';
148                 }
149             } else {
150                 $record->grade = unformat_float($record->grade);
151             }
153             // Note: Do not count the seconds when comparing modified dates.
154             $skip = false;
155             $stalemodificationdate = ($usergrade && $usergrade->timemodified > ($modified + 60));
157             if ($usergrade && $usergrade->grade == $record->grade) {
158                 // Skip - grade not modified.
159                 $skip = true;
160             } else if (!isset($record->grade) || $record->grade === '' || $record->grade < 0) {
161                 // Skip - grade has no value.
162                 $skip = true;
163             } else if (!$ignoremodified && $stalemodificationdate) {
164                 // Skip - grade has been modified.
165                 $skip = true;
166             } else if ($this->assignment->grading_disabled($record->user->id)) {
167                 // Skip grade is locked.
168                 $skip = true;
169             } else if (($this->assignment->get_instance()->grade > -1) &&
170                       (($record->grade < 0) || ($record->grade > $this->assignment->get_instance()->grade))) {
171                 // Out of range.
172                 $skip = true;
173             }
175             if (!$skip) {
176                 $grade = $this->assignment->get_user_grade($record->user->id, true);
178                 $grade->grade = $record->grade;
179                 $grade->grader = $USER->id;
180                 if ($this->assignment->update_grade($grade)) {
181                     $this->assignment->notify_grade_modified($grade);
182                     $updatecount += 1;
183                 }
184             }
186             if ($ignoremodified || !$stalemodificationdate) {
187                 foreach ($record->feedback as $feedback) {
188                     $plugin = $feedback['plugin'];
189                     $field = $feedback['field'];
190                     $newvalue = $feedback['value'];
191                     $description = $feedback['description'];
192                     $oldvalue = '';
193                     if ($usergrade) {
194                         $oldvalue = $plugin->get_editor_text($field, $usergrade->id);
195                         if (empty($oldvalue)) {
196                             $oldvalue = '';
197                         }
198                     }
199                     if ($newvalue != $oldvalue) {
200                         $updatecount += 1;
201                         $grade = $this->assignment->get_user_grade($record->user->id, true);
202                         $this->assignment->notify_grade_modified($grade);
203                         $plugin->set_editor_text($field, $newvalue, $grade->id);
205                         // If this is the gradebook comments plugin - post an update to the gradebook.
206                         if (($plugin->get_subtype() . '_' . $plugin->get_type()) == $gradebookplugin) {
207                             $grade->feedbacktext = $plugin->text_for_gradebook($grade);
208                             $grade->feedbackformat = $plugin->format_for_gradebook($grade);
209                             $this->assignment->update_grade($grade);
210                         }
211                     }
212                 }
213             }
214         }
215         $gradeimporter->close(true);
217         $renderer = $this->assignment->get_renderer();
218         $o = '';
220         $o .= $renderer->render(new assign_header($this->assignment->get_instance(),
221                                                   $this->assignment->get_context(),
222                                                   false,
223                                                   $this->assignment->get_course_module()->id,
224                                                   get_string('importgrades', 'assignfeedback_offline')));
225         $o .= $renderer->box(get_string('updatedgrades', 'assignfeedback_offline', $updatecount));
226         $url = new moodle_url('view.php',
227                               array('id'=>$this->assignment->get_course_module()->id,
228                                     'action'=>'grading'));
229         $o .= $renderer->continue_button($url);
230         $o .= $renderer->render_footer();
231         return $o;
232     }
234     /**
235      * Display upload grades form
236      *
237      * @return string The response html
238      */
239     public function upload_grades() {
240         global $CFG, $USER;
242         require_capability('mod/assign:grade', $this->assignment->get_context());
243         require_once($CFG->dirroot . '/mod/assign/feedback/offline/uploadgradesform.php');
244         require_once($CFG->dirroot . '/mod/assign/feedback/offline/importgradesform.php');
245         require_once($CFG->dirroot . '/mod/assign/feedback/offline/importgradeslib.php');
246         require_once($CFG->libdir . '/csvlib.class.php');
248         $mform = new assignfeedback_offline_upload_grades_form(null,
249                                                               array('context'=>$this->assignment->get_context(),
250                                                                     'cm'=>$this->assignment->get_course_module()->id));
252         $o = '';
254         $confirm = optional_param('confirm', 0, PARAM_BOOL);
255         $renderer = $this->assignment->get_renderer();
257         if ($mform->is_cancelled()) {
258             redirect(new moodle_url('view.php',
259                                     array('id'=>$this->assignment->get_course_module()->id,
260                                           'action'=>'grading')));
261             return;
262         } else if (($data = $mform->get_data()) &&
263                    ($csvdata = $mform->get_file_content('gradesfile'))) {
265             $importid = csv_import_reader::get_new_iid('assignfeedback_offline');
266             $gradeimporter = new assignfeedback_offline_grade_importer($importid, $this->assignment,
267                     $data->encoding, $data->separator);
268             // File exists and was valid.
269             $ignoremodified = !empty($data->ignoremodified);
271             $draftid = $data->gradesfile;
273             // Preview import.
275             $mform = new assignfeedback_offline_import_grades_form(null, array('assignment'=>$this->assignment,
276                                                                        'csvdata'=>$csvdata,
277                                                                        'ignoremodified'=>$ignoremodified,
278                                                                        'gradeimporter'=>$gradeimporter,
279                                                                        'draftid'=>$draftid));
281             $o .= $renderer->render(new assign_header($this->assignment->get_instance(),
282                                                             $this->assignment->get_context(),
283                                                             false,
284                                                             $this->assignment->get_course_module()->id,
285                                                             get_string('confirmimport', 'assignfeedback_offline')));
286             $o .= $renderer->render(new assign_form('confirmimport', $mform));
287             $o .= $renderer->render_footer();
288         } else if ($confirm) {
289             $importid = optional_param('importid', 0, PARAM_INT);
290             $draftid = optional_param('draftid', 0, PARAM_INT);
291             $encoding = optional_param('encoding', 'utf-8', PARAM_ALPHAEXT);
292             $separator = optional_param('separator', 'comma', PARAM_ALPHA);
293             $ignoremodified = optional_param('ignoremodified', 0, PARAM_BOOL);
294             $gradeimporter = new assignfeedback_offline_grade_importer($importid, $this->assignment, $encoding, $separator);
295             $mform = new assignfeedback_offline_import_grades_form(null, array('assignment'=>$this->assignment,
296                                                                        'csvdata'=>'',
297                                                                        'ignoremodified'=>$ignoremodified,
298                                                                        'gradeimporter'=>$gradeimporter,
299                                                                        'draftid'=>$draftid));
300             if ($mform->is_cancelled()) {
301                 redirect(new moodle_url('view.php',
302                                         array('id'=>$this->assignment->get_course_module()->id,
303                                               'action'=>'grading')));
304                 return;
305             }
307             $o .= $this->process_import_grades($draftid, $importid, $ignoremodified, $encoding, $separator);
308         } else {
310             $o .= $renderer->render(new assign_header($this->assignment->get_instance(),
311                                                             $this->assignment->get_context(),
312                                                             false,
313                                                             $this->assignment->get_course_module()->id,
314                                                             get_string('uploadgrades', 'assignfeedback_offline')));
315             $o .= $renderer->render(new assign_form('batchuploadfiles', $mform));
316             $o .= $renderer->render_footer();
317         }
319         return $o;
320     }
322     /**
323      * Download a marking worksheet
324      *
325      * @return string The response html
326      */
327     public function download_grades() {
328         global $CFG;
330         require_capability('mod/assign:grade', $this->assignment->get_context());
331         require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
333         $groupmode = groups_get_activity_groupmode($this->assignment->get_course_module());
334         // All users.
335         $groupid = 0;
336         $groupname = '';
337         if ($groupmode) {
338             $groupid = groups_get_activity_group($this->assignment->get_course_module(), true);
339             $groupname = groups_get_group_name($groupid) . '-';
340         }
341         $filename = clean_filename(get_string('offlinegradingworksheet', 'assignfeedback_offline') . '-' .
342                                    $this->assignment->get_course()->shortname . '-' .
343                                    $this->assignment->get_instance()->name . '-' .
344                                    $groupname .
345                                    $this->assignment->get_course_module()->id);
347         $table = new assign_grading_table($this->assignment, 0, '', 0, false, $filename);
349         $table->out(0, false);
350         return;
351     }
353     /**
354      * Print a sub page in this plugin
355      *
356      * @param string $action - The plugin action
357      * @return string The response html
358      */
359     public function view_page($action) {
360         if ($action == 'downloadgrades') {
361             return $this->download_grades();
362         } else if ($action == 'uploadgrades') {
363             return $this->upload_grades();
364         }
366         return '';
367     }
369     /**
370      * Return a list of the grading actions performed by this plugin
371      * This plugin supports upload zip
372      *
373      * @return array The list of grading actions
374      */
375     public function get_grading_actions() {
376         return array('uploadgrades'=>get_string('uploadgrades', 'assignfeedback_offline'),
377                     'downloadgrades'=>get_string('downloadgrades', 'assignfeedback_offline'));
378     }
380     /**
381      * Override the default is_enabled to disable this plugin if advanced grading is active
382      *
383      * @return bool
384      */
385     public function is_enabled() {
386         if ($this->enabledcache === null) {
387             $gradingmanager = get_grading_manager($this->assignment->get_context(), 'mod_assign', 'submissions');
388             $controller = $gradingmanager->get_active_controller();
389             $active = !empty($controller);
391             if ($active) {
392                 $this->enabledcache = false;
393             } else {
394                 $this->enabledcache = parent::is_enabled();
395             }
396         }
397         return $this->enabledcache;
398     }
400     /**
401      * Do not show this plugin in the grading table or on the front page
402      *
403      * @return bool
404      */
405     public function has_user_summary() {
406         return false;
407     }