Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
 
26
namespace mod_forum\message\inbound;
27
 
28
defined('MOODLE_INTERNAL') || die();
29
 
30
require_once($CFG->dirroot . '/mod/forum/lib.php');
31
require_once($CFG->dirroot . '/repository/lib.php');
32
require_once($CFG->libdir . '/completionlib.php');
33
 
34
/**
35
 * A Handler to process replies to forum posts.
36
 *
37
 * @copyright  2014 Andrew Nicols
38
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39
 */
40
class 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
     * @throws \core\message\inbound\processing_failed_exception
65
     * @param \stdClass $messagedata The Inbound Message record
66
     * @param \stdClass $messagedata The message data packet
67
     * @return bool Whether the message was successfully processed.
68
     */
69
    public function process_message(\stdClass $record, \stdClass $messagedata) {
1441 ariadna 70
        global $CFG, $DB, $USER;
1 efrain 71
 
72
        // Load the post being replied to.
73
        $post = $DB->get_record('forum_posts', array('id' => $record->datavalue));
74
        if (!$post) {
75
            mtrace("--> Unable to find a post matching with id {$record->datavalue}");
76
            return false;
77
        }
78
 
79
        // Load the discussion that this post is in.
80
        $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
81
        if (!$post) {
82
            mtrace("--> Unable to find the discussion for post {$record->datavalue}");
83
            return false;
84
        }
85
 
86
        // Load the other required data.
87
        $forum = $DB->get_record('forum', array('id' => $discussion->forum));
88
        $course = $DB->get_record('course', array('id' => $forum->course));
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 \core\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)) {
122
            $data = new \stdClass();
123
            $data->forum = $forum;
124
            throw new \core\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 \core\message\inbound\processing_failed_exception('messageinboundthresholdhit', 'mod_forum', $data);
135
        }
136
 
137
        $subject = clean_param($messagedata->envelope->subject, PARAM_TEXT);
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.
1441 ariadna 141
            mtrace("--> Note: Post subject matched discussion name. Optimising from {$subject} to {$discussion->name}");
142
            $subject = $discussion->name;
1 efrain 143
        } else if (strpos($subject, $post->subject)) {
144
            // The replied-to post's subject is mentioned in the e-mail subject.
145
            // Use the previous post's subject instead of the e-mail subject.
1441 ariadna 146
            mtrace("--> Note: Post subject matched original post subject. Optimising from {$subject} to {$post->subject}");
147
            $subject = $post->subject;
1 efrain 148
        }
149
 
150
        $addpost = new \stdClass();
151
        $addpost->course       = $course->id;
152
        $addpost->forum        = $forum->id;
153
        $addpost->discussion   = $discussion->id;
154
        $addpost->modified     = $messagedata->timestamp;
155
        $addpost->subject      = $subject;
156
        $addpost->parent       = $post->id;
157
        $addpost->itemid       = file_get_unused_draft_itemid();
158
        $addpost->deleted      = 0;
159
 
160
        list ($message, $format) = self::remove_quoted_text($messagedata);
161
        $addpost->message = $message;
162
        $addpost->messageformat = $format;
163
 
164
        // We don't trust text coming from e-mail.
165
        $addpost->messagetrust = false;
166
 
167
        // Find all attachments. If format is plain text, treat inline attachments as regular ones.
168
        $attachments = !empty($messagedata->attachments['attachment']) ? $messagedata->attachments['attachment'] : [];
169
        $inlineattachments = [];
170
        if (!empty($messagedata->attachments['inline'])) {
171
            if ($addpost->messageformat == FORMAT_HTML) {
172
                $inlineattachments = $messagedata->attachments['inline'];
173
            } else {
174
                $attachments = array_merge($attachments, $messagedata->attachments['inline']);
175
            }
176
        }
177
 
178
        // Add attachments to the post.
179
        if ($attachments) {
180
            $attachmentcount = count($attachments);
181
            if (!forum_can_create_attachment($forum, $modcontext)) {
182
                // Attachments are not allowed.
183
                mtrace("--> User does not have permission to attach files in this forum. Rejecting e-mail.");
184
 
185
                $data = new \stdClass();
186
                $data->forum = $forum;
187
                $data->attachmentcount = $attachmentcount;
188
                throw new \core\message\inbound\processing_failed_exception('messageinboundattachmentdisallowed', 'mod_forum', $data);
189
            }
190
 
191
            if ($forum->maxattachments < $attachmentcount) {
192
                // Too many attachments.
193
                mtrace("--> User attached {$attachmentcount} files when only {$forum->maxattachments} where allowed. "
194
                     . " Rejecting e-mail.");
195
 
196
                $data = new \stdClass();
197
                $data->forum = $forum;
198
                $data->attachmentcount = $attachmentcount;
199
                throw new \core\message\inbound\processing_failed_exception('messageinboundfilecountexceeded', 'mod_forum', $data);
200
            }
201
 
202
            $filesize = 0;
203
            $addpost->attachments  = file_get_unused_draft_itemid();
204
            foreach ($attachments as $attachment) {
205
                mtrace("--> Processing {$attachment->filename} as an attachment.");
206
                $this->process_attachment('*', $usercontext, $addpost->attachments, $attachment);
207
                $filesize += $attachment->filesize;
208
            }
209
 
1441 ariadna 210
            $maxbytes = get_user_max_upload_file_size($modcontext, $CFG->maxbytes, $course->maxbytes, $forum->maxbytes);
211
            if ($maxbytes < $filesize) {
1 efrain 212
                // Too many attachments.
1441 ariadna 213
                mtrace("--> User attached {$filesize} bytes of files when only {$maxbytes} were allowed. Rejecting e-mail.");
1 efrain 214
                $data = new \stdClass();
215
                $data->forum = $forum;
1441 ariadna 216
                $data->maxbytes = display_size($maxbytes);
1 efrain 217
                $data->filesize = display_size($filesize);
218
                throw new \core\message\inbound\processing_failed_exception('messageinboundfilesizeexceeded', 'mod_forum', $data);
219
            }
220
        }
221
 
222
        // Process any files in the message itself.
223
        if ($inlineattachments) {
224
            foreach ($inlineattachments as $attachment) {
225
                mtrace("--> Processing {$attachment->filename} as an inline attachment.");
226
                $this->process_attachment('*', $usercontext, $addpost->itemid, $attachment);
227
 
228
                // Convert the contentid link in the message.
229
                $draftfile = \moodle_url::make_draftfile_url($addpost->itemid, '/', $attachment->filename);
230
                $addpost->message = preg_replace('/cid:' . $attachment->contentid . '/', $draftfile, $addpost->message);
231
            }
232
        }
233
 
234
        // Insert the message content now.
235
        $addpost->id = forum_add_new_post($addpost, true);
236
 
237
        // Log the new post creation.
238
        $params = array(
239
            'context' => $modcontext,
240
            'objectid' => $addpost->id,
241
            'other' => array(
242
                'discussionid'  => $discussion->id,
243
                'forumid'       => $forum->id,
244
                'forumtype'     => $forum->type,
245
            )
246
        );
247
        $event = \mod_forum\event\post_created::create($params);
248
        $event->add_record_snapshot('forum_posts', $addpost);
249
        $event->add_record_snapshot('forum_discussions', $discussion);
250
        $event->trigger();
251
 
252
        // Update completion state.
253
        $completion = new \completion_info($course);
254
        if ($completion->is_enabled($cm) && ($forum->completionreplies || $forum->completionposts)) {
255
            $completion->update_state($cm, COMPLETION_COMPLETE);
256
 
257
            mtrace("--> Updating completion status for user {$USER->id} in forum {$forum->id} for post {$addpost->id}.");
258
        }
259
 
260
        mtrace("--> Created a post {$addpost->id} in {$discussion->id}.");
261
        return $addpost;
262
    }
263
 
264
    /**
265
     * Process attachments included in a message.
266
     *
267
     * @param string[] $acceptedtypes String The mimetypes of the acceptable attachment types.
268
     * @param \context_user $context context_user The context of the user creating this attachment.
269
     * @param int $itemid int The itemid to store this attachment under.
270
     * @param \stdClass $attachment stdClass The Attachment data to store.
271
     * @return \stored_file
272
     */
273
    protected function process_attachment($acceptedtypes, \context_user $context, $itemid, \stdClass $attachment) {
274
        global $USER, $CFG;
275
 
276
        // Create the file record.
277
        $record = new \stdClass();
278
        $record->filearea   = 'draft';
279
        $record->component  = 'user';
280
 
281
        $record->itemid     = $itemid;
282
        $record->license    = $CFG->sitedefaultlicense;
283
        $record->author     = fullname($USER);
284
        $record->contextid  = $context->id;
285
        $record->userid     = $USER->id;
286
 
287
        // All files sent by e-mail should have a flat structure.
288
        $record->filepath   = '/';
289
 
290
        $record->filename = $attachment->filename;
291
 
292
        mtrace("--> Attaching {$record->filename} to " .
293
               "/{$record->contextid}/{$record->component}/{$record->filearea}/" .
294
               "{$record->itemid}{$record->filepath}{$record->filename}");
295
 
296
        $fs = get_file_storage();
297
        return $fs->create_file_from_string($record, $attachment->content);
298
    }
299
 
300
    /**
301
     * Return the content of any success notification to be sent.
302
     * Both an HTML and Plain Text variant must be provided.
303
     *
304
     * @param \stdClass $messagedata The message data.
305
     * @param \stdClass $handlerresult The record for the newly created post.
306
     * @return \stdClass with keys `html` and `plain`.
307
     */
308
    public function get_success_message(\stdClass $messagedata, $handlerresult) {
309
        $a = new \stdClass();
310
        $a->subject = $handlerresult->subject;
311
        $discussionurl = new \moodle_url('/mod/forum/discuss.php', array('d' => $handlerresult->discussion));
312
        $discussionurl->set_anchor('p' . $handlerresult->id);
313
        $a->discussionurl = $discussionurl->out();
314
 
315
        $message = new \stdClass();
316
        $message->plain = get_string('postbymailsuccess', 'mod_forum', $a);
317
        $message->html = get_string('postbymailsuccess_html', 'mod_forum', $a);
318
        return $message;
319
    }
320
}