MDL-48148 mod_forum: Use correct original subject when handling replies
[moodle.git] / mod / forum / classes / message / inbound / reply_handler.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  * A Handler to process replies to forum posts.
19  *
20  * @package    mod_forum
21  * @subpackage core_message
22  * @copyright  2014 Andrew Nicols
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 namespace mod_forum\message\inbound;
28 defined('MOODLE_INTERNAL') || die();
30 require_once($CFG->dirroot . '/mod/forum/lib.php');
31 require_once($CFG->dirroot . '/repository/lib.php');
33 /**
34  * A Handler to process replies to forum posts.
35  *
36  * @copyright  2014 Andrew Nicols
37  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38  */
39 class reply_handler extends \core\message\inbound\handler {
41     /**
42      * Return a description for the current handler.
43      *
44      * @return string
45      */
46     public function get_description() {
47         return get_string('reply_handler', 'mod_forum');
48     }
50     /**
51      * Return a short name for the current handler.
52      * This appears in the admin pages as a human-readable name.
53      *
54      * @return string
55      */
56     public function get_name() {
57         return get_string('reply_handler_name', 'mod_forum');
58     }
60     /**
61      * Process a message received and validated by the Inbound Message processor.
62      *
63      * @throws \core\message\inbound\processing_failed_exception
64      * @param \stdClass $messagedata The Inbound Message record
65      * @param \stdClass $messagedata The message data packet
66      * @return bool Whether the message was successfully processed.
67      */
68     public function process_message(\stdClass $record, \stdClass $messagedata) {
69         global $DB, $USER;
71         // Load the post being replied to.
72         $post = $DB->get_record('forum_posts', array('id' => $record->datavalue));
73         if (!$post) {
74             mtrace("--> Unable to find a post matching with id {$record->datavalue}");
75             return false;
76         }
78         // Load the discussion that this post is in.
79         $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
80         if (!$post) {
81             mtrace("--> Unable to find the discussion for post {$record->datavalue}");
82             return false;
83         }
85         // Load the other required data.
86         $forum = $DB->get_record('forum', array('id' => $discussion->forum));
87         $course = $DB->get_record('course', array('id' => $forum->course));
88         $cm = get_fast_modinfo($course->id)->instances['forum'][$forum->id];
89         $modcontext = \context_module::instance($cm->id);
90         $usercontext = \context_user::instance($USER->id);
92         // Make sure user can post in this discussion.
93         $canpost = true;
94         if (!forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext)) {
95             $canpost = false;
96         }
98         if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
99             $groupmode = $cm->groupmode;
100         } else {
101             $groupmode = $course->groupmode;
102         }
103         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $modcontext)) {
104             if ($discussion->groupid == -1) {
105                 $canpost = false;
106             } else {
107                 if (!groups_is_member($discussion->groupid)) {
108                     $canpost = false;
109                 }
110             }
111         }
113         if (!$canpost) {
114             $data = new \stdClass();
115             $data->forum = $forum;
116             throw new \core\message\inbound\processing_failed_exception('messageinboundnopostforum', 'mod_forum', $data);
117         }
119         // And check the availability.
120         if (!\core_availability\info_module::is_user_visible($cm, $USER, true)) {
121             $data = new \stdClass();
122             $data->forum = $forum;
123             throw new \core\message\inbound\processing_failed_exception('messageinboundforumhidden', 'mod_forum', $data);
124         }
126         // Before we add this we must check that the user will not exceed the blocking threshold.
127         // This should result in an appropriate reply.
128         $thresholdwarning = forum_check_throttling($forum, $cm);
129         if (!empty($thresholdwarning) && !$thresholdwarning->canpost) {
130             $data = new \stdClass();
131             $data->forum = $forum;
132             $data->message = get_string($thresholdwarning->errorcode, $thresholdwarning->module, $thresholdwarning->additional);
133             throw new \core\message\inbound\processing_failed_exception('messageinboundthresholdhit', 'mod_forum', $data);
134         }
136         $subject = clean_param($messagedata->envelope->subject, PARAM_TEXT);
137         $restring = get_string('re', 'forum');
138         if (strpos($subject, $discussion->name)) {
139             // The discussion name is mentioned in the e-mail subject. This is probably just the standard reply. Use the
140             // standard reply subject instead.
141             $newsubject = $restring . ' ' . $discussion->name;
142             mtrace("--> Note: Post subject matched discussion name. Optimising from {$subject} to {$newsubject}");
143             $subject = $newsubject;
144         } else if (strpos($subject, $post->subject)) {
145             // The replied-to post's subject is mentioned in the e-mail subject.
146             // Use the previous post's subject instead of the e-mail subject.
147             $newsubject = $post->subject;
148             if (!strpos($restring, $post->subject)) {
149                 // The previous post did not contain a re string, add it.
150                 $newsubject = $restring . ' ' . $newsubject;
151             }
152             mtrace("--> Note: Post subject matched original post subject. Optimising from {$subject} to {$newsubject}");
153             $subject = $newsubject;
154         }
156         $addpost = new \stdClass();
157         $addpost->course       = $course->id;
158         $addpost->forum        = $forum->id;
159         $addpost->discussion   = $discussion->id;
160         $addpost->modified     = $messagedata->timestamp;
161         $addpost->subject      = $subject;
162         $addpost->parent       = $post->id;
163         $addpost->itemid       = file_get_unused_draft_itemid();
165         if (!empty($messagedata->html)) {
166             $addpost->message = $messagedata->html;
167             $addpost->messageformat = FORMAT_HTML;
168         } else {
169             $addpost->message = $messagedata->plain;
170             $addpost->messageformat = FORMAT_PLAIN;
171         }
173         // We don't trust text coming from e-mail.
174         $addpost->messagetrust = false;
176         // Add attachments to the post.
177         if (!empty($messagedata->attachments['attachment']) && count($messagedata->attachments['attachment'])) {
178             $attachmentcount = count($messagedata->attachments['attachment']);
179             if (empty($forum->maxattachments) || $forum->maxbytes == 1 ||
180                     !has_capability('mod/forum:createattachment', $modcontext)) {
181                 // Attachments are not allowed.
182                 mtrace("--> User does not have permission to attach files in this forum. Rejecting e-mail.");
184                 $data = new \stdClass();
185                 $data->forum = $forum;
186                 $data->attachmentcount = $attachmentcount;
187                 throw new \core\message\inbound\processing_failed_exception('messageinboundattachmentdisallowed', 'mod_forum', $data);
188             }
190             if ($forum->maxattachments < $attachmentcount) {
191                 // Too many attachments.
192                 mtrace("--> User attached {$attachmentcount} files when only {$forum->maxattachments} where allowed. "
193                      . " Rejecting e-mail.");
195                 $data = new \stdClass();
196                 $data->forum = $forum;
197                 $data->attachmentcount = $attachmentcount;
198                 throw new \core\message\inbound\processing_failed_exception('messageinboundfilecountexceeded', 'mod_forum', $data);
199             }
201             $filesize = 0;
202             $addpost->attachments  = file_get_unused_draft_itemid();
203             foreach ($messagedata->attachments['attachment'] as $attachment) {
204                 mtrace("--> Processing {$attachment->filename} as an attachment.");
205                 $this->process_attachment('*', $usercontext, $addpost->attachments, $attachment);
206                 $filesize += $attachment->filesize;
207             }
209             if ($forum->maxbytes < $filesize) {
210                 // Too many attachments.
211                 mtrace("--> User attached {$filesize} bytes of files when only {$forum->maxbytes} where allowed. "
212                      . "Rejecting e-mail.");
213                 $data = new \stdClass();
214                 $data->forum = $forum;
215                 $data->maxbytes = display_size($forum->maxbytes);
216                 $data->filesize = display_size($filesize);
217                 throw new \core\message\inbound\processing_failed_exception('messageinboundfilesizeexceeded', 'mod_forum', $data);
218             }
219         }
221         // Process any files in the message itself.
222         if (!empty($messagedata->attachments['inline'])) {
223             foreach ($messagedata->attachments['inline'] as $attachment) {
224                 mtrace("--> Processing {$attachment->filename} as an inline attachment.");
225                 $this->process_attachment('*', $usercontext, $addpost->itemid, $attachment);
227                 // Convert the contentid link in the message.
228                 $draftfile = \moodle_url::make_draftfile_url($addpost->itemid, '/', $attachment->filename);
229                 $addpost->message = preg_replace('/cid:' . $attachment->contentid . '/', $draftfile, $addpost->message);
230             }
231         }
233         // Insert the message content now.
234         $addpost->id = forum_add_new_post($addpost, true);
236         // Log the new post creation.
237         $params = array(
238             'context' => $modcontext,
239             'objectid' => $addpost->id,
240             'other' => array(
241                 'discussionid'  => $discussion->id,
242                 'forumid'       => $forum->id,
243                 'forumtype'     => $forum->type,
244             )
245         );
246         $event = \mod_forum\event\post_created::create($params);
247         $event->add_record_snapshot('forum_posts', $addpost);
248         $event->add_record_snapshot('forum_discussions', $discussion);
249         $event->trigger();
251         mtrace("--> Created a post {$addpost->id} in {$discussion->id}.");
252         return $addpost;
253     }
255     /**
256      * Process attachments included in a message.
257      *
258      * @param string[] $acceptedtypes String The mimetypes of the acceptable attachment types.
259      * @param \context_user $context context_user The context of the user creating this attachment.
260      * @param int $itemid int The itemid to store this attachment under.
261      * @param \stdClass $attachment stdClass The Attachment data to store.
262      * @return \stored_file
263      */
264     protected function process_attachment($acceptedtypes, \context_user $context, $itemid, \stdClass $attachment) {
265         global $USER, $CFG;
267         // Create the file record.
268         $record = new \stdClass();
269         $record->filearea   = 'draft';
270         $record->component  = 'user';
272         $record->itemid     = $itemid;
273         $record->license    = $CFG->sitedefaultlicense;
274         $record->author     = fullname($USER);
275         $record->contextid  = $context->id;
276         $record->userid     = $USER->id;
278         // All files sent by e-mail should have a flat structure.
279         $record->filepath   = '/';
281         $record->filename = $attachment->filename;
283         mtrace("--> Attaching {$record->filename} to " .
284                "/{$record->contextid}/{$record->component}/{$record->filearea}/" .
285                "{$record->itemid}{$record->filepath}{$record->filename}");
287         $fs = get_file_storage();
288         return $fs->create_file_from_string($record, $attachment->content);
289     }
292     /**
293      * Return the content of any success notification to be sent.
294      * Both an HTML and Plain Text variant must be provided.
295      *
296      * @param \stdClass $messagedata The message data.
297      * @param \stdClass $handlerresult The record for the newly created post.
298      * @return \stdClass with keys `html` and `plain`.
299      */
300     public function get_success_message(\stdClass $messagedata, $handlerresult) {
301         $a = new \stdClass();
302         $a->subject = $handlerresult->subject;
303         $discussionurl = new \moodle_url('/mod/forum/discuss.php', array('d' => $handlerresult->discussion));
304         $a->discussionurl = $discussionurl->out();
306         $message = new \stdClass();
307         $message->plain = get_string('postbymailsuccess', 'mod_forum', $a);
308         $message->html = get_string('postbymailsuccess_html', 'mod_forum', $a);
309         return $message;
310     }