MDL-55188 events: First deprecation of eventslib.php
[moodle.git] / mod / assign / submission / file / 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 submission plugin
19  *
20  * This class provides all the functionality for the new assign module.
21  *
22  * @package assignsubmission_file
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 // File areas for file submission assignment.
30 define('ASSIGNSUBMISSION_FILE_MAXSUMMARYFILES', 5);
31 define('ASSIGNSUBMISSION_FILE_FILEAREA', 'submission_files');
33 /**
34  * Library class for file submission plugin extending submission plugin base class
35  *
36  * @package   assignsubmission_file
37  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
38  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39  */
40 class assign_submission_file extends assign_submission_plugin {
42     /**
43      * Get the name of the file submission plugin
44      * @return string
45      */
46     public function get_name() {
47         return get_string('file', 'assignsubmission_file');
48     }
50     /**
51      * Get file submission information from the database
52      *
53      * @param int $submissionid
54      * @return mixed
55      */
56     private function get_file_submission($submissionid) {
57         global $DB;
58         return $DB->get_record('assignsubmission_file', array('submission'=>$submissionid));
59     }
61     /**
62      * Get the default setting for file submission plugin
63      *
64      * @param MoodleQuickForm $mform The form to add elements to
65      * @return void
66      */
67     public function get_settings(MoodleQuickForm $mform) {
68         global $CFG, $COURSE;
70         $defaultmaxfilesubmissions = $this->get_config('maxfilesubmissions');
71         $defaultmaxsubmissionsizebytes = $this->get_config('maxsubmissionsizebytes');
72         if ($this->assignment->has_instance()) {
73             $defaultfiletypes = $this->get_config('filetypeslist');
74         } else {
75             $defaultfiletypes = get_config('assignsubmission_file', 'filetypes');
76         }
77         $defaultfiletypes = (string)$defaultfiletypes;
79         $settings = array();
80         $options = array();
81         for ($i = 1; $i <= get_config('assignsubmission_file', 'maxfiles'); $i++) {
82             $options[$i] = $i;
83         }
85         $name = get_string('maxfilessubmission', 'assignsubmission_file');
86         $mform->addElement('select', 'assignsubmission_file_maxfiles', $name, $options);
87         $mform->addHelpButton('assignsubmission_file_maxfiles',
88                               'maxfilessubmission',
89                               'assignsubmission_file');
90         $mform->setDefault('assignsubmission_file_maxfiles', $defaultmaxfilesubmissions);
91         $mform->disabledIf('assignsubmission_file_maxfiles', 'assignsubmission_file_enabled', 'notchecked');
93         $choices = get_max_upload_sizes($CFG->maxbytes,
94                                         $COURSE->maxbytes,
95                                         get_config('assignsubmission_file', 'maxbytes'));
97         $settings[] = array('type' => 'select',
98                             'name' => 'maxsubmissionsizebytes',
99                             'description' => get_string('maximumsubmissionsize', 'assignsubmission_file'),
100                             'options'=> $choices,
101                             'default'=> $defaultmaxsubmissionsizebytes);
103         $name = get_string('maximumsubmissionsize', 'assignsubmission_file');
104         $mform->addElement('select', 'assignsubmission_file_maxsizebytes', $name, $choices);
105         $mform->addHelpButton('assignsubmission_file_maxsizebytes',
106                               'maximumsubmissionsize',
107                               'assignsubmission_file');
108         $mform->setDefault('assignsubmission_file_maxsizebytes', $defaultmaxsubmissionsizebytes);
109         $mform->disabledIf('assignsubmission_file_maxsizebytes',
110                            'assignsubmission_file_enabled',
111                            'notchecked');
113         $name = get_string('acceptedfiletypes', 'assignsubmission_file');
114         $mform->addElement('filetypes', 'assignsubmission_file_filetypes', $name);
115         $mform->addHelpButton('assignsubmission_file_filetypes', 'acceptedfiletypes', 'assignsubmission_file');
116         $mform->setDefault('assignsubmission_file_filetypes', $defaultfiletypes);
117         $mform->disabledIf('assignsubmission_file_filetypes', 'assignsubmission_file_enabled', 'notchecked');
118     }
120     /**
121      * Save the settings for file submission plugin
122      *
123      * @param stdClass $data
124      * @return bool
125      */
126     public function save_settings(stdClass $data) {
127         $this->set_config('maxfilesubmissions', $data->assignsubmission_file_maxfiles);
128         $this->set_config('maxsubmissionsizebytes', $data->assignsubmission_file_maxsizebytes);
130         if (!empty($data->assignsubmission_file_filetypes)) {
131             $this->set_config('filetypeslist', $data->assignsubmission_file_filetypes);
132         } else {
133             $this->set_config('filetypeslist', '');
134         }
136         return true;
137     }
139     /**
140      * File format options
141      *
142      * @return array
143      */
144     private function get_file_options() {
145         $fileoptions = array('subdirs' => 1,
146                                 'maxbytes' => $this->get_config('maxsubmissionsizebytes'),
147                                 'maxfiles' => $this->get_config('maxfilesubmissions'),
148                                 'accepted_types' => $this->get_configured_typesets(),
149                                 'return_types' => (FILE_INTERNAL | FILE_CONTROLLED_LINK));
150         if ($fileoptions['maxbytes'] == 0) {
151             // Use module default.
152             $fileoptions['maxbytes'] = get_config('assignsubmission_file', 'maxbytes');
153         }
154         return $fileoptions;
155     }
157     /**
158      * Add elements to submission form
159      *
160      * @param mixed $submission stdClass|null
161      * @param MoodleQuickForm $mform
162      * @param stdClass $data
163      * @return bool
164      */
165     public function get_form_elements($submission, MoodleQuickForm $mform, stdClass $data) {
166         global $OUTPUT;
168         if ($this->get_config('maxfilesubmissions') <= 0) {
169             return false;
170         }
172         $fileoptions = $this->get_file_options();
173         $submissionid = $submission ? $submission->id : 0;
175         $data = file_prepare_standard_filemanager($data,
176                                                   'files',
177                                                   $fileoptions,
178                                                   $this->assignment->get_context(),
179                                                   'assignsubmission_file',
180                                                   ASSIGNSUBMISSION_FILE_FILEAREA,
181                                                   $submissionid);
182         $mform->addElement('filemanager', 'files_filemanager', $this->get_name(), null, $fileoptions);
184         return true;
185     }
187     /**
188      * Count the number of files
189      *
190      * @param int $submissionid
191      * @param string $area
192      * @return int
193      */
194     private function count_files($submissionid, $area) {
195         $fs = get_file_storage();
196         $files = $fs->get_area_files($this->assignment->get_context()->id,
197                                      'assignsubmission_file',
198                                      $area,
199                                      $submissionid,
200                                      'id',
201                                      false);
203         return count($files);
204     }
206     /**
207      * Save the files and trigger plagiarism plugin, if enabled,
208      * to scan the uploaded files via events trigger
209      *
210      * @param stdClass $submission
211      * @param stdClass $data
212      * @return bool
213      */
214     public function save(stdClass $submission, stdClass $data) {
215         global $USER, $DB;
217         $fileoptions = $this->get_file_options();
219         $data = file_postupdate_standard_filemanager($data,
220                                                      'files',
221                                                      $fileoptions,
222                                                      $this->assignment->get_context(),
223                                                      'assignsubmission_file',
224                                                      ASSIGNSUBMISSION_FILE_FILEAREA,
225                                                      $submission->id);
227         $filesubmission = $this->get_file_submission($submission->id);
229         // Plagiarism code event trigger when files are uploaded.
231         $fs = get_file_storage();
232         $files = $fs->get_area_files($this->assignment->get_context()->id,
233                                      'assignsubmission_file',
234                                      ASSIGNSUBMISSION_FILE_FILEAREA,
235                                      $submission->id,
236                                      'id',
237                                      false);
239         $count = $this->count_files($submission->id, ASSIGNSUBMISSION_FILE_FILEAREA);
241         $params = array(
242             'context' => context_module::instance($this->assignment->get_course_module()->id),
243             'courseid' => $this->assignment->get_course()->id,
244             'objectid' => $submission->id,
245             'other' => array(
246                 'content' => '',
247                 'pathnamehashes' => array_keys($files)
248             )
249         );
250         if (!empty($submission->userid) && ($submission->userid != $USER->id)) {
251             $params['relateduserid'] = $submission->userid;
252         }
253         $event = \assignsubmission_file\event\assessable_uploaded::create($params);
254         $event->set_legacy_files($files);
255         $event->trigger();
257         $groupname = null;
258         $groupid = 0;
259         // Get the group name as other fields are not transcribed in the logs and this information is important.
260         if (empty($submission->userid) && !empty($submission->groupid)) {
261             $groupname = $DB->get_field('groups', 'name', array('id' => $submission->groupid), MUST_EXIST);
262             $groupid = $submission->groupid;
263         } else {
264             $params['relateduserid'] = $submission->userid;
265         }
267         // Unset the objectid and other field from params for use in submission events.
268         unset($params['objectid']);
269         unset($params['other']);
270         $params['other'] = array(
271             'submissionid' => $submission->id,
272             'submissionattempt' => $submission->attemptnumber,
273             'submissionstatus' => $submission->status,
274             'filesubmissioncount' => $count,
275             'groupid' => $groupid,
276             'groupname' => $groupname
277         );
279         if ($filesubmission) {
280             $filesubmission->numfiles = $this->count_files($submission->id,
281                                                            ASSIGNSUBMISSION_FILE_FILEAREA);
282             $updatestatus = $DB->update_record('assignsubmission_file', $filesubmission);
283             $params['objectid'] = $filesubmission->id;
285             $event = \assignsubmission_file\event\submission_updated::create($params);
286             $event->set_assign($this->assignment);
287             $event->trigger();
288             return $updatestatus;
289         } else {
290             $filesubmission = new stdClass();
291             $filesubmission->numfiles = $this->count_files($submission->id,
292                                                            ASSIGNSUBMISSION_FILE_FILEAREA);
293             $filesubmission->submission = $submission->id;
294             $filesubmission->assignment = $this->assignment->get_instance()->id;
295             $filesubmission->id = $DB->insert_record('assignsubmission_file', $filesubmission);
296             $params['objectid'] = $filesubmission->id;
298             $event = \assignsubmission_file\event\submission_created::create($params);
299             $event->set_assign($this->assignment);
300             $event->trigger();
301             return $filesubmission->id > 0;
302         }
303     }
305     /**
306      * Produce a list of files suitable for export that represent this feedback or submission
307      *
308      * @param stdClass $submission The submission
309      * @param stdClass $user The user record - unused
310      * @return array - return an array of files indexed by filename
311      */
312     public function get_files(stdClass $submission, stdClass $user) {
313         $result = array();
314         $fs = get_file_storage();
316         $files = $fs->get_area_files($this->assignment->get_context()->id,
317                                      'assignsubmission_file',
318                                      ASSIGNSUBMISSION_FILE_FILEAREA,
319                                      $submission->id,
320                                      'timemodified',
321                                      false);
323         foreach ($files as $file) {
324             // Do we return the full folder path or just the file name?
325             if (isset($submission->exportfullpath) && $submission->exportfullpath == false) {
326                 $result[$file->get_filename()] = $file;
327             } else {
328                 $result[$file->get_filepath().$file->get_filename()] = $file;
329             }
330         }
331         return $result;
332     }
334     /**
335      * Display the list of files  in the submission status table
336      *
337      * @param stdClass $submission
338      * @param bool $showviewlink Set this to true if the list of files is long
339      * @return string
340      */
341     public function view_summary(stdClass $submission, & $showviewlink) {
342         $count = $this->count_files($submission->id, ASSIGNSUBMISSION_FILE_FILEAREA);
344         // Show we show a link to view all files for this plugin?
345         $showviewlink = $count > ASSIGNSUBMISSION_FILE_MAXSUMMARYFILES;
346         if ($count <= ASSIGNSUBMISSION_FILE_MAXSUMMARYFILES) {
347             return $this->assignment->render_area_files('assignsubmission_file',
348                                                         ASSIGNSUBMISSION_FILE_FILEAREA,
349                                                         $submission->id);
350         } else {
351             return get_string('countfiles', 'assignsubmission_file', $count);
352         }
353     }
355     /**
356      * No full submission view - the summary contains the list of files and that is the whole submission
357      *
358      * @param stdClass $submission
359      * @return string
360      */
361     public function view(stdClass $submission) {
362         return $this->assignment->render_area_files('assignsubmission_file',
363                                                     ASSIGNSUBMISSION_FILE_FILEAREA,
364                                                     $submission->id);
365     }
369     /**
370      * Return true if this plugin can upgrade an old Moodle 2.2 assignment of this type
371      * and version.
372      *
373      * @param string $type
374      * @param int $version
375      * @return bool True if upgrade is possible
376      */
377     public function can_upgrade($type, $version) {
379         $uploadsingletype ='uploadsingle';
380         $uploadtype ='upload';
382         if (($type == $uploadsingletype || $type == $uploadtype) && $version >= 2011112900) {
383             return true;
384         }
385         return false;
386     }
389     /**
390      * Upgrade the settings from the old assignment
391      * to the new plugin based one
392      *
393      * @param context $oldcontext - the old assignment context
394      * @param stdClass $oldassignment - the old assignment data record
395      * @param string $log record log events here
396      * @return bool Was it a success? (false will trigger rollback)
397      */
398     public function upgrade_settings(context $oldcontext, stdClass $oldassignment, & $log) {
399         global $DB;
401         if ($oldassignment->assignmenttype == 'uploadsingle') {
402             $this->set_config('maxfilesubmissions', 1);
403             $this->set_config('maxsubmissionsizebytes', $oldassignment->maxbytes);
404             return true;
405         } else if ($oldassignment->assignmenttype == 'upload') {
406             $this->set_config('maxfilesubmissions', $oldassignment->var1);
407             $this->set_config('maxsubmissionsizebytes', $oldassignment->maxbytes);
409             // Advanced file upload uses a different setting to do the same thing.
410             $DB->set_field('assign',
411                            'submissiondrafts',
412                            $oldassignment->var4,
413                            array('id'=>$this->assignment->get_instance()->id));
415             // Convert advanced file upload "hide description before due date" setting.
416             $alwaysshow = 0;
417             if (!$oldassignment->var3) {
418                 $alwaysshow = 1;
419             }
420             $DB->set_field('assign',
421                            'alwaysshowdescription',
422                            $alwaysshow,
423                            array('id'=>$this->assignment->get_instance()->id));
424             return true;
425         }
426     }
428     /**
429      * Upgrade the submission from the old assignment to the new one
430      *
431      * @param context $oldcontext The context of the old assignment
432      * @param stdClass $oldassignment The data record for the old oldassignment
433      * @param stdClass $oldsubmission The data record for the old submission
434      * @param stdClass $submission The data record for the new submission
435      * @param string $log Record upgrade messages in the log
436      * @return bool true or false - false will trigger a rollback
437      */
438     public function upgrade(context $oldcontext,
439                             stdClass $oldassignment,
440                             stdClass $oldsubmission,
441                             stdClass $submission,
442                             & $log) {
443         global $DB;
445         $filesubmission = new stdClass();
447         $filesubmission->numfiles = $oldsubmission->numfiles;
448         $filesubmission->submission = $submission->id;
449         $filesubmission->assignment = $this->assignment->get_instance()->id;
451         if (!$DB->insert_record('assignsubmission_file', $filesubmission) > 0) {
452             $log .= get_string('couldnotconvertsubmission', 'mod_assign', $submission->userid);
453             return false;
454         }
456         // Now copy the area files.
457         $this->assignment->copy_area_files_for_upgrade($oldcontext->id,
458                                                         'mod_assignment',
459                                                         'submission',
460                                                         $oldsubmission->id,
461                                                         $this->assignment->get_context()->id,
462                                                         'assignsubmission_file',
463                                                         ASSIGNSUBMISSION_FILE_FILEAREA,
464                                                         $submission->id);
466         return true;
467     }
469     /**
470      * The assignment has been deleted - cleanup
471      *
472      * @return bool
473      */
474     public function delete_instance() {
475         global $DB;
476         // Will throw exception on failure.
477         $DB->delete_records('assignsubmission_file',
478                             array('assignment'=>$this->assignment->get_instance()->id));
480         return true;
481     }
483     /**
484      * Formatting for log info
485      *
486      * @param stdClass $submission The submission
487      * @return string
488      */
489     public function format_for_log(stdClass $submission) {
490         // Format the info for each submission plugin (will be added to log).
491         $filecount = $this->count_files($submission->id, ASSIGNSUBMISSION_FILE_FILEAREA);
493         return get_string('numfilesforlog', 'assignsubmission_file', $filecount);
494     }
496     /**
497      * Return true if there are no submission files
498      * @param stdClass $submission
499      */
500     public function is_empty(stdClass $submission) {
501         return $this->count_files($submission->id, ASSIGNSUBMISSION_FILE_FILEAREA) == 0;
502     }
504     /**
505      * Determine if a submission is empty
506      *
507      * This is distinct from is_empty in that it is intended to be used to
508      * determine if a submission made before saving is empty.
509      *
510      * @param stdClass $data The submission data
511      * @return bool
512      */
513     public function submission_is_empty(stdClass $data) {
514         global $USER;
515         $fs = get_file_storage();
516         // Get a count of all the draft files, excluding any directories.
517         $files = $fs->get_area_files(context_user::instance($USER->id)->id,
518                                      'user',
519                                      'draft',
520                                      $data->files_filemanager,
521                                      'id',
522                                      false);
523         return count($files) == 0;
524     }
526     /**
527      * Get file areas returns a list of areas this plugin stores files
528      * @return array - An array of fileareas (keys) and descriptions (values)
529      */
530     public function get_file_areas() {
531         return array(ASSIGNSUBMISSION_FILE_FILEAREA=>$this->get_name());
532     }
534     /**
535      * Copy the student's submission from a previous submission. Used when a student opts to base their resubmission
536      * on the last submission.
537      * @param stdClass $sourcesubmission
538      * @param stdClass $destsubmission
539      */
540     public function copy_submission(stdClass $sourcesubmission, stdClass $destsubmission) {
541         global $DB;
543         // Copy the files across.
544         $contextid = $this->assignment->get_context()->id;
545         $fs = get_file_storage();
546         $files = $fs->get_area_files($contextid,
547                                      'assignsubmission_file',
548                                      ASSIGNSUBMISSION_FILE_FILEAREA,
549                                      $sourcesubmission->id,
550                                      'id',
551                                      false);
552         foreach ($files as $file) {
553             $fieldupdates = array('itemid' => $destsubmission->id);
554             $fs->create_file_from_storedfile($fieldupdates, $file);
555         }
557         // Copy the assignsubmission_file record.
558         if ($filesubmission = $this->get_file_submission($sourcesubmission->id)) {
559             unset($filesubmission->id);
560             $filesubmission->submission = $destsubmission->id;
561             $DB->insert_record('assignsubmission_file', $filesubmission);
562         }
563         return true;
564     }
566     /**
567      * Return a description of external params suitable for uploading a file submission from a webservice.
568      *
569      * @return external_description|null
570      */
571     public function get_external_parameters() {
572         return array(
573             'files_filemanager' => new external_value(
574                 PARAM_INT,
575                 'The id of a draft area containing files for this submission.',
576                 VALUE_OPTIONAL
577             )
578         );
579     }
581     /**
582      * Return the plugin configs for external functions.
583      *
584      * @return array the list of settings
585      * @since Moodle 3.2
586      */
587     public function get_config_for_external() {
588         global $CFG;
590         $configs = $this->get_config();
592         // Get a size in bytes.
593         if ($configs->maxsubmissionsizebytes == 0) {
594             $configs->maxsubmissionsizebytes = get_max_upload_file_size($CFG->maxbytes, $this->assignment->get_course()->maxbytes,
595                                                                         get_config('assignsubmission_file', 'maxbytes'));
596         }
597         return (array) $configs;
598     }
600     /**
601      * Get the type sets configured for this assignment.
602      *
603      * @return array('groupname', 'mime/type', ...)
604      */
605     private function get_configured_typesets() {
606         $typeslist = (string)$this->get_config('filetypeslist');
608         $util = new \core_form\filetypes_util();
609         $sets = $util->normalize_file_types($typeslist);
611         return $sets;
612     }