MDL-43289 mod_assign: Creation of new submission events.
[moodle.git] / mod / assign / submission / onlinetext / 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 onlinetext submission plugin
19  *
20  * This class provides all the functionality for the new assign module.
21  *
22  * @package assignsubmission_onlinetext
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();
28 // File area for online text submission assignment.
29 define('ASSIGNSUBMISSION_ONLINETEXT_FILEAREA', 'submissions_onlinetext');
31 /**
32  * library class for onlinetext submission plugin extending submission plugin base class
33  *
34  * @package assignsubmission_onlinetext
35  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
36  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37  */
38 class assign_submission_onlinetext extends assign_submission_plugin {
40     /**
41      * Get the name of the online text submission plugin
42      * @return string
43      */
44     public function get_name() {
45         return get_string('onlinetext', 'assignsubmission_onlinetext');
46     }
49     /**
50      * Get onlinetext submission information from the database
51      *
52      * @param  int $submissionid
53      * @return mixed
54      */
55     private function get_onlinetext_submission($submissionid) {
56         global $DB;
58         return $DB->get_record('assignsubmission_onlinetext', array('submission'=>$submissionid));
59     }
61     /**
62      * Add form elements for settings
63      *
64      * @param mixed $submission can be null
65      * @param MoodleQuickForm $mform
66      * @param stdClass $data
67      * @return true if elements were added to the form
68      */
69     public function get_form_elements($submission, MoodleQuickForm $mform, stdClass $data) {
70         $elements = array();
72         $editoroptions = $this->get_edit_options();
73         $submissionid = $submission ? $submission->id : 0;
75         if (!isset($data->onlinetext)) {
76             $data->onlinetext = '';
77         }
78         if (!isset($data->onlinetextformat)) {
79             $data->onlinetextformat = editors_get_preferred_format();
80         }
82         if ($submission) {
83             $onlinetextsubmission = $this->get_onlinetext_submission($submission->id);
84             if ($onlinetextsubmission) {
85                 $data->onlinetext = $onlinetextsubmission->onlinetext;
86                 $data->onlinetextformat = $onlinetextsubmission->onlineformat;
87             }
89         }
91         $data = file_prepare_standard_editor($data,
92                                              'onlinetext',
93                                              $editoroptions,
94                                              $this->assignment->get_context(),
95                                              'assignsubmission_onlinetext',
96                                              ASSIGNSUBMISSION_ONLINETEXT_FILEAREA,
97                                              $submissionid);
98         $mform->addElement('editor', 'onlinetext_editor', $this->get_name(), null, $editoroptions);
100         return true;
101     }
103     /**
104      * Editor format options
105      *
106      * @return array
107      */
108     private function get_edit_options() {
109          $editoroptions = array(
110            'noclean' => false,
111            'maxfiles' => EDITOR_UNLIMITED_FILES,
112            'maxbytes' => $this->assignment->get_course()->maxbytes,
113            'context' => $this->assignment->get_context(),
114            'return_types' => FILE_INTERNAL | FILE_EXTERNAL
115         );
116         return $editoroptions;
117     }
119     /**
120      * Save data to the database and trigger plagiarism plugin,
121      * if enabled, to scan the uploaded content via events trigger
122      *
123      * @param stdClass $submission
124      * @param stdClass $data
125      * @return bool
126      */
127     public function save(stdClass $submission, stdClass $data) {
128         global $USER, $DB;
130         $editoroptions = $this->get_edit_options();
132         $data = file_postupdate_standard_editor($data,
133                                                 'onlinetext',
134                                                 $editoroptions,
135                                                 $this->assignment->get_context(),
136                                                 'assignsubmission_onlinetext',
137                                                 ASSIGNSUBMISSION_ONLINETEXT_FILEAREA,
138                                                 $submission->id);
140         $onlinetextsubmission = $this->get_onlinetext_submission($submission->id);
142         $fs = get_file_storage();
144         $files = $fs->get_area_files($this->assignment->get_context()->id,
145                                      'assignsubmission_onlinetext',
146                                      ASSIGNSUBMISSION_ONLINETEXT_FILEAREA,
147                                      $submission->id,
148                                      'id',
149                                      false);
151         $params = array(
152             'context' => context_module::instance($this->assignment->get_course_module()->id),
153             'courseid' => $this->assignment->get_course()->id,
154             'objectid' => $submission->id,
155             'other' => array(
156                 'pathnamehashes' => array_keys($files),
157                 'content' => trim($data->onlinetext),
158                 'format' => $data->onlinetext_editor['format']
159             )
160         );
161         $event = \assignsubmission_onlinetext\event\assessable_uploaded::create($params);
162         $event->trigger();
164         $groupname = null;
165         $groupid = 0;
166         // Get the group name as other fields are not transcribed in the logs and this information is important.
167         if (empty($submission->userid) && !empty($submission->groupid)) {
168             $groupname = $DB->get_field('groups', 'name', array('id' => $submission->groupid), '*', MUST_EXIST);
169             $groupid = $submission->groupid;
170         } else {
171             $params['relateduserid'] = $submission->userid;
172         }
174         $count = count_words($data->onlinetext);
176         // Unset the objectid and other field from params for use in submission events.
177         unset($params['objectid']);
178         unset($params['other']);
179         $params['other'] = array(
180             'submissionid' => $submission->id,
181             'submissionattempt' => $submission->attemptnumber,
182             'submissionstatus' => $submission->status,
183             'onlinetextwordcount' => $count,
184             'groupid' => $groupid,
185             'groupname' => $groupname
186         );
188         if ($onlinetextsubmission) {
190             $onlinetextsubmission->onlinetext = $data->onlinetext;
191             $onlinetextsubmission->onlineformat = $data->onlinetext_editor['format'];
192             $params['objectid'] = $onlinetextsubmission->id;
193             $updatestatus = $DB->update_record('assignsubmission_onlinetext', $onlinetextsubmission);
194             $event = \assignsubmission_onlinetext\event\submission_updated::create($params);
195             $event->trigger();
196             return $updatestatus;
197         } else {
199             $onlinetextsubmission = new stdClass();
200             $onlinetextsubmission->onlinetext = $data->onlinetext;
201             $onlinetextsubmission->onlineformat = $data->onlinetext_editor['format'];
203             $onlinetextsubmission->submission = $submission->id;
204             $onlinetextsubmission->assignment = $this->assignment->get_instance()->id;
205             $onlinetextsubmission->id = $DB->insert_record('assignsubmission_onlinetext', $onlinetextsubmission);
206             $params['objectid'] = $onlinetextsubmission->id;
207             $event = \assignsubmission_onlinetext\event\submission_created::create($params);
208             $event->trigger();
209             return $onlinetextsubmission->id > 0;
210         }
211     }
213     /**
214      * Return a list of the text fields that can be imported/exported by this plugin
215      *
216      * @return array An array of field names and descriptions. (name=>description, ...)
217      */
218     public function get_editor_fields() {
219         return array('onlinetext' => get_string('pluginname', 'assignsubmission_comments'));
220     }
222     /**
223      * Get the saved text content from the editor
224      *
225      * @param string $name
226      * @param int $submissionid
227      * @return string
228      */
229     public function get_editor_text($name, $submissionid) {
230         if ($name == 'onlinetext') {
231             $onlinetextsubmission = $this->get_onlinetext_submission($submissionid);
232             if ($onlinetextsubmission) {
233                 return $onlinetextsubmission->onlinetext;
234             }
235         }
237         return '';
238     }
240     /**
241      * Get the content format for the editor
242      *
243      * @param string $name
244      * @param int $submissionid
245      * @return int
246      */
247     public function get_editor_format($name, $submissionid) {
248         if ($name == 'onlinetext') {
249             $onlinetextsubmission = $this->get_onlinetext_submission($submissionid);
250             if ($onlinetextsubmission) {
251                 return $onlinetextsubmission->onlineformat;
252             }
253         }
255         return 0;
256     }
259      /**
260       * Display onlinetext word count in the submission status table
261       *
262       * @param stdClass $submission
263       * @param bool $showviewlink - If the summary has been truncated set this to true
264       * @return string
265       */
266     public function view_summary(stdClass $submission, & $showviewlink) {
267         global $CFG;
269         $onlinetextsubmission = $this->get_onlinetext_submission($submission->id);
270         // Always show the view link.
271         $showviewlink = true;
273         if ($onlinetextsubmission) {
274             $text = $this->assignment->render_editor_content(ASSIGNSUBMISSION_ONLINETEXT_FILEAREA,
275                                                              $onlinetextsubmission->submission,
276                                                              $this->get_type(),
277                                                              'onlinetext',
278                                                              'assignsubmission_onlinetext');
280             $shorttext = shorten_text($text, 140);
281             $plagiarismlinks = '';
283             if (!empty($CFG->enableplagiarism)) {
284                 require_once($CFG->libdir . '/plagiarismlib.php');
286                 $plagiarismlinks .= plagiarism_get_links(array('userid' => $submission->userid,
287                     'content' => trim($text),
288                     'cmid' => $this->assignment->get_course_module()->id,
289                     'course' => $this->assignment->get_course()->id,
290                     'assignment' => $submission->assignment));
291             }
292             if ($text != $shorttext) {
293                 $wordcount = get_string('numwords', 'assignsubmission_onlinetext', count_words($text));
295                 return $shorttext . $plagiarismlinks . $wordcount;
296             } else {
297                 return $shorttext . $plagiarismlinks;
298             }
299         }
300         return '';
301     }
303     /**
304      * Produce a list of files suitable for export that represent this submission.
305      *
306      * @param stdClass $submission - For this is the submission data
307      * @param stdClass $user - This is the user record for this submission
308      * @return array - return an array of files indexed by filename
309      */
310     public function get_files(stdClass $submission, stdClass $user) {
311         global $DB;
313         $files = array();
314         $onlinetextsubmission = $this->get_onlinetext_submission($submission->id);
316         if ($onlinetextsubmission) {
317             $finaltext = $this->assignment->download_rewrite_pluginfile_urls($onlinetextsubmission->onlinetext, $user, $this);
318             $formattedtext = format_text($finaltext,
319                                          $onlinetextsubmission->onlineformat,
320                                          array('context'=>$this->assignment->get_context()));
321             $submissioncontent = '<html><body>'. $formattedtext . '</body></html>';
323             $filename = get_string('onlinetextfilename', 'assignsubmission_onlinetext');
324             $files[$filename] = array($submissioncontent);
326             $fs = get_file_storage();
328             $fsfiles = $fs->get_area_files($this->assignment->get_context()->id,
329                                            'assignsubmission_onlinetext',
330                                            ASSIGNSUBMISSION_ONLINETEXT_FILEAREA,
331                                            $submission->id,
332                                            'timemodified',
333                                            false);
335             foreach ($fsfiles as $file) {
336                 $files[$file->get_filename()] = $file;
337             }
338         }
340         return $files;
341     }
343     /**
344      * Display the saved text content from the editor in the view table
345      *
346      * @param stdClass $submission
347      * @return string
348      */
349     public function view(stdClass $submission) {
350         $result = '';
352         $onlinetextsubmission = $this->get_onlinetext_submission($submission->id);
354         if ($onlinetextsubmission) {
356             // Render for portfolio API.
357             $result .= $this->assignment->render_editor_content(ASSIGNSUBMISSION_ONLINETEXT_FILEAREA,
358                                                                 $onlinetextsubmission->submission,
359                                                                 $this->get_type(),
360                                                                 'onlinetext',
361                                                                 'assignsubmission_onlinetext');
363         }
365         return $result;
366     }
368     /**
369      * Return true if this plugin can upgrade an old Moodle 2.2 assignment of this type and version.
370      *
371      * @param string $type old assignment subtype
372      * @param int $version old assignment version
373      * @return bool True if upgrade is possible
374      */
375     public function can_upgrade($type, $version) {
376         if ($type == 'online' && $version >= 2011112900) {
377             return true;
378         }
379         return false;
380     }
383     /**
384      * Upgrade the settings from the old assignment to the new plugin based one
385      *
386      * @param context $oldcontext - the database for the old assignment context
387      * @param stdClass $oldassignment - the database for the old assignment instance
388      * @param string $log record log events here
389      * @return bool Was it a success?
390      */
391     public function upgrade_settings(context $oldcontext, stdClass $oldassignment, & $log) {
392         // No settings to upgrade.
393         return true;
394     }
396     /**
397      * Upgrade the submission from the old assignment to the new one
398      *
399      * @param context $oldcontext - the database for the old assignment context
400      * @param stdClass $oldassignment The data record for the old assignment
401      * @param stdClass $oldsubmission The data record for the old submission
402      * @param stdClass $submission The data record for the new submission
403      * @param string $log Record upgrade messages in the log
404      * @return bool true or false - false will trigger a rollback
405      */
406     public function upgrade(context $oldcontext,
407                             stdClass $oldassignment,
408                             stdClass $oldsubmission,
409                             stdClass $submission,
410                             & $log) {
411         global $DB;
413         $onlinetextsubmission = new stdClass();
414         $onlinetextsubmission->onlinetext = $oldsubmission->data1;
415         $onlinetextsubmission->onlineformat = $oldsubmission->data2;
417         $onlinetextsubmission->submission = $submission->id;
418         $onlinetextsubmission->assignment = $this->assignment->get_instance()->id;
420         if ($onlinetextsubmission->onlinetext === null) {
421             $onlinetextsubmission->onlinetext = '';
422         }
424         if ($onlinetextsubmission->onlineformat === null) {
425             $onlinetextsubmission->onlineformat = editors_get_preferred_format();
426         }
428         if (!$DB->insert_record('assignsubmission_onlinetext', $onlinetextsubmission) > 0) {
429             $log .= get_string('couldnotconvertsubmission', 'mod_assign', $submission->userid);
430             return false;
431         }
433         // Now copy the area files.
434         $this->assignment->copy_area_files_for_upgrade($oldcontext->id,
435                                                         'mod_assignment',
436                                                         'submission',
437                                                         $oldsubmission->id,
438                                                         $this->assignment->get_context()->id,
439                                                         'assignsubmission_onlinetext',
440                                                         ASSIGNSUBMISSION_ONLINETEXT_FILEAREA,
441                                                         $submission->id);
442         return true;
443     }
445     /**
446      * Formatting for log info
447      *
448      * @param stdClass $submission The new submission
449      * @return string
450      */
451     public function format_for_log(stdClass $submission) {
452         // Format the info for each submission plugin (will be logged).
453         $onlinetextsubmission = $this->get_onlinetext_submission($submission->id);
454         $onlinetextloginfo = '';
455         $onlinetextloginfo .= get_string('numwordsforlog',
456                                          'assignsubmission_onlinetext',
457                                          count_words($onlinetextsubmission->onlinetext));
459         return $onlinetextloginfo;
460     }
462     /**
463      * The assignment has been deleted - cleanup
464      *
465      * @return bool
466      */
467     public function delete_instance() {
468         global $DB;
469         $DB->delete_records('assignsubmission_onlinetext',
470                             array('assignment'=>$this->assignment->get_instance()->id));
472         return true;
473     }
475     /**
476      * No text is set for this plugin
477      *
478      * @param stdClass $submission
479      * @return bool
480      */
481     public function is_empty(stdClass $submission) {
482         $onlinetextsubmission = $this->get_onlinetext_submission($submission->id);
484         return empty($onlinetextsubmission->onlinetext);
485     }
487     /**
488      * Get file areas returns a list of areas this plugin stores files
489      * @return array - An array of fileareas (keys) and descriptions (values)
490      */
491     public function get_file_areas() {
492         return array(ASSIGNSUBMISSION_ONLINETEXT_FILEAREA=>$this->get_name());
493     }
495     /**
496      * Copy the student's submission from a previous submission. Used when a student opts to base their resubmission
497      * on the last submission.
498      * @param stdClass $sourcesubmission
499      * @param stdClass $destsubmission
500      */
501     public function copy_submission(stdClass $sourcesubmission, stdClass $destsubmission) {
502         global $DB;
504         // Copy the files across (attached via the text editor).
505         $contextid = $this->assignment->get_context()->id;
506         $fs = get_file_storage();
507         $files = $fs->get_area_files($contextid, 'assignsubmission_onlinetext',
508                                      ASSIGNSUBMISSION_ONLINETEXT_FILEAREA, $sourcesubmission->id, 'id', false);
509         foreach ($files as $file) {
510             $fieldupdates = array('itemid' => $destsubmission->id);
511             $fs->create_file_from_storedfile($fieldupdates, $file);
512         }
514         // Copy the assignsubmission_onlinetext record.
515         $onlinetextsubmission = $this->get_onlinetext_submission($sourcesubmission->id);
516         if ($onlinetextsubmission) {
517             unset($onlinetextsubmission->id);
518             $onlinetextsubmission->submission = $destsubmission->id;
519             $DB->insert_record('assignsubmission_onlinetext', $onlinetextsubmission);
520         }
521         return true;
522     }
524     /**
525      * Return a description of external params suitable for uploading an onlinetext submission from a webservice.
526      *
527      * @return external_description|null
528      */
529     public function get_external_parameters() {
530         $editorparams = array('text' => new external_value(PARAM_TEXT, 'The text for this submission.'),
531                               'format' => new external_value(PARAM_INT, 'The format for this submission'),
532                               'itemid' => new external_value(PARAM_INT, 'The draft area id for files attached to the submission'));
533         $editorstructure = new external_single_structure($editorparams);
534         return array('onlinetext_editor' => $editorstructure);
535     }