MDL-3714 mod_forum: Add an inbound message handler
[moodle.git] / mod / forum / classes / message / inbound / reply_handler.php
CommitLineData
91223df6
AN
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/>.
16
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 */
25
26namespace mod_forum\message\inbound;
27
28defined('MOODLE_INTERNAL') || die();
29
30require_once($CFG->dirroot . '/mod/forum/lib.php');
31require_once($CFG->dirroot . '/repository/lib.php');
32
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
40class reply_handler extends \core\message\inbound\handler {
41
42 /**
43 * Return a description for the current handler.
44 *
45 * @return string
46 */
47 public function get_description() {
48 return get_string('reply_handler', 'mod_forum');
49 }
50
51 /**
52 * Return a short name for the current handler.
53 * This appears in the admin pages as a human-readable name.
54 *
55 * @return string
56 */
57 public function get_name() {
58 return get_string('reply_handler_name', 'mod_forum');
59 }
60
61 /**
62 * Process a message received and validated by the Inbound Message processor.
63 *
64 * @param $messagedata The Inbound Message record
65 * @param $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, $CFG, $USER;
70
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 }
77
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 }
84
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 $coursecontext = \context_course::instance($course->id);
89 $cm = get_fast_modinfo($course->id)->instances['forum'][$forum->id];
90 $modcontext = \context_module::instance($cm->id);
91 $usercontext = \context_user::instance($USER->id);
92
93 // Make sure user can post in this discussion.
94 $canpost = true;
95 if (!forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext)) {
96 $canpost = false;
97 }
98
99 if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
100 $groupmode = $cm->groupmode;
101 } else {
102 $groupmode = $course->groupmode;
103 }
104 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $modcontext)) {
105 if ($discussion->groupid == -1) {
106 $canpost = false;
107 } else {
108 if (!groups_is_member($discussion->groupid)) {
109 $canpost = false;
110 }
111 }
112 }
113
114 if (!$canpost) {
115 $data = new \stdClass();
116 $data->forum = $forum;
117 throw new \message\inbound\processing_failed_exception('messageinboundnopostforum', 'mod_forum', $data);
118 }
119
120 // And check the availability.
121 if (!\core_availability\info_module::is_user_visible($cm, $USER, true)) {
122 $data = new \stdClass();
123 $data->forum = $forum;
124 throw new \message\inbound\processing_failed_exception('messageinboundforumhidden', 'mod_forum', $data);
125 }
126
127 // Before we add this we must check that the user will not exceed the blocking threshold.
128 // This should result in an appropriate reply.
129 $thresholdwarning = forum_check_throttling($forum, $cm);
130 if (!empty($thresholdwarning) && !$thresholdwarning->canpost) {
131 $data = new \stdClass();
132 $data->forum = $forum;
133 $data->message = get_string($thresholdwarning->errorcode, $thresholdwarning->module, $thresholdwarning->additional);
134 throw new \message\inbound\processing_failed_exception('messageinboundthresholdhit', 'mod_forum', $data);
135 }
136
137 $addpost = new \stdClass();
138 $addpost->course = $course->id;
139 $addpost->forum = $forum->id;
140 $addpost->discussion = $discussion->id;
141 $addpost->modified = $messagedata->timestamp;
142 $addpost->subject = clean_param($messagedata->envelope->subject, PARAM_TEXT);
143 $addpost->parent = $post->id;
144 $addpost->itemid = file_get_unused_draft_itemid();
145
146 if (!empty($messagedata->html)) {
147 $addpost->message = $messagedata->html;
148 $addpost->messageformat = FORMAT_HTML;
149 } else {
150 $addpost->message = $messagedata->plain;
151 $addpost->messageformat = FORMAT_PLAIN;
152 }
153
154 // We don't trust text coming from e-mail.
155 $addpost->messagetrust = false;
156
157 // Add attachments to the post.
158 if (!empty($messagedata->attachments['attachment']) && count($messagedata->attachments['attachment'])) {
159 $attachmentcount = count($messagedata->attachments['attachment']);
160 if (empty($forum->maxattachments) || $forum->maxbytes == 1 ||
161 !has_capability('mod/forum:createattachment', $modcontext)) {
162 // Attachments are not allowed.
163 mtrace("--> User does not have permission to attach files in this forum. Rejecting e-mail.");
164
165 $data = new \stdClass();
166 $data->forum = $forum;
167 $data->attachmentcount = $attachmentcount;
168 throw new \message\inbound\processing_failed_exception('messageinboundattachmentdisallowed', 'mod_forum', $data);
169 }
170
171 if ($forum->maxattachments < $attachmentcount) {
172 // Too many attachments.
173 mtrace("--> User attached {$attachmentcount} files when only {$forum->maxattachments} where allowed. "
174 . " Rejecting e-mail.");
175
176 $data = new \stdClass();
177 $data->forum = $forum;
178 $data->attachmentcount = $attachmentcount;
179 throw new \message\inbound\processing_failed_exception('messageinboundfilecountexceeded', 'mod_forum', $data);
180 }
181
182 $filesize = 0;
183 $addpost->attachments = file_get_unused_draft_itemid();
184 foreach ($messagedata->attachments['attachment'] as $attachment) {
185 mtrace("--> Processing {$attachment->filename} as an attachment.");
186 $this->process_attachment('*', $usercontext, $addpost->attachments, $attachment);
187 $filesize += $attachment->filesize;
188 }
189
190 if ($forum->maxbytes < $filesize) {
191 // Too many attachments.
192 mtrace("--> User attached {$filesize} bytes of files when only {$forum->maxbytes} where allowed. "
193 . "Rejecting e-mail.");
194 $data = new \stdClass();
195 $data->forum = $forum;
196 $data->maxbytes = display_size($forum->maxbytes);
197 $data->filesize = display_size($filesize);
198 throw new \message\inbound\processing_failed_exception('messageinboundfilesizeexceeded', 'mod_forum', $data);
199 }
200 }
201
202 // Process any files in the message itself.
203 if (!empty($messagedata->attachments['inline'])) {
204 foreach ($messagedata->attachments['inline'] as $attachment) {
205 mtrace("--> Processing {$attachment->filename} as an inline attachment.");
206 $this->process_attachment('*', $usercontext, $addpost->itemid, $attachment);
207
208 // Convert the contentid link in the message.
209 $draftfile = \moodle_url::make_draftfile_url($addpost->itemid, '/', $attachment->filename);
210 $addpost->message = preg_replace('/cid:' . $attachment->contentid . '/', $draftfile, $addpost->message);
211 }
212 }
213
214 // Insert the message content now.
215 $addpost->id = forum_add_new_post($addpost, true);
216
217 // Log the new post creation.
218 $params = array(
219 'context' => $modcontext,
220 'objectid' => $addpost->id,
221 'other' => array(
222 'discussionid' => $discussion->id,
223 'forumid' => $forum->id,
224 'forumtype' => $forum->type,
225 )
226 );
227 $event = \mod_forum\event\post_created::create($params);
228 $event->add_record_snapshot('forum_posts', $addpost);
229 $event->add_record_snapshot('forum_discussions', $discussion);
230 $event->trigger();
231
232 mtrace("--> Created a post {$addpost->id} in {$discussion->id}.");
233 return $addpost;
234 }
235
236 /**
237 * Process attachments included in a message.
238 *
239 * @param $acceptedtypes String The mimetypes of the acceptable attachment types.
240 * @param $context context_user The context of the user creating this attachment.
241 * @param $itemid int The itemid to store this attachment under.
242 * @param $attachment stdClass The Attachment data to store.
243 */
244 protected function process_attachment($acceptedtypes, \context_user $context, $itemid, \stdClass $attachment) {
245 global $DB, $USER, $CFG;
246
247 // Create the file record.
248 $record = new \stdClass();
249 $record->filearea = 'draft';
250 $record->component = 'user';
251
252 $record->itemid = $itemid;
253 $record->license = $CFG->sitedefaultlicense;
254 $record->author = fullname($USER);
255 $record->contextid = $context->id;
256 $record->userid = $USER->id;
257
258 // All files sent by e-mail should have a flat structure.
259 $record->filepath = '/';
260
261 $record->filename = $attachment->filename;
262
263 mtrace("--> Attaching {$record->filename} to " .
264 "/{$record->contextid}/{$record->component}/{$record->filearea}/" .
265 "{$record->itemid}{$record->filepath}{$record->filename}");
266
267 $fs = get_file_storage();
268 return $fs->create_file_from_string($record, $attachment->content);
269 }
270
271
272 /**
273 * Return the content of any success notification to be sent.
274 * Both an HTML and Plain Text variant must be provided.
275 *
276 * @param \stdClass $messagedata The message data.
277 * @param \stdClass $handlerresult The record for the newly created post.
278 * @return \stdClass with keys `html` and `plain`.
279 */
280 public function get_success_message(\stdClass $messagedata, $handlerresult) {
281 $a = new \stdClass();
282 $a->subject = $handlerresult->subject;
283 $discussionurl = new \moodle_url('/mod/forum/discuss.php', array('d' => $handlerresult->discussion));
284 $a->discussionurl = $discussionurl->out();
285
286 $message = new \stdClass();
287 $message->plain = get_string('postbymailsuccess', 'mod_forum', $a);
288 $message->html = get_string('postbymailsuccess_html', 'mod_forum', $a);
289 return $message;
290 }
291
292}