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
 * This file defines an adhoc task to send notifications.
19
 *
20
 * @package    mod_forum
21
 * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
namespace mod_forum\task;
26
 
27
defined('MOODLE_INTERNAL') || die();
28
 
29
/**
30
 * Adhoc task to send user forum notifications.
31
 *
32
 * @package    mod_forum
33
 * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
34
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35
 */
36
class send_user_notifications extends \core\task\adhoc_task {
37
 
38
    // Use the logging trait to get some nice, juicy, logging.
39
    use \core\task\logging_trait;
40
 
41
    /**
42
     * @var \stdClass   A shortcut to $USER.
43
     */
44
    protected $recipient;
45
 
46
    /**
47
     * @var \stdClass[] List of courses the messages are in, indexed by courseid.
48
     */
49
    protected $courses = [];
50
 
51
    /**
52
     * @var \stdClass[] List of forums the messages are in, indexed by courseid.
53
     */
54
    protected $forums = [];
55
 
56
    /**
57
     * @var int[] List of IDs for forums in each course.
58
     */
59
    protected $courseforums = [];
60
 
61
    /**
62
     * @var \stdClass[] List of discussions the messages are in, indexed by forumid.
63
     */
64
    protected $discussions = [];
65
 
66
    /**
67
     * @var \stdClass[] List of IDs for discussions in each forum.
68
     */
69
    protected $forumdiscussions = [];
70
 
71
    /**
72
     * @var \stdClass[] List of posts the messages are in, indexed by discussionid.
73
     */
74
    protected $posts = [];
75
 
76
    /**
77
     * @var bool[] Whether the user can view fullnames for each forum.
78
     */
79
    protected $viewfullnames = [];
80
 
81
    /**
82
     * @var bool[] Whether the user can post in each discussion.
83
     */
84
    protected $canpostto = [];
85
 
86
    /**
87
     * @var \renderer[] The renderers.
88
     */
89
    protected $renderers = [];
90
 
91
    /**
92
     * @var \core\message\inbound\address_manager The inbound message address manager.
93
     */
94
    protected $inboundmanager;
95
 
96
    /**
97
     * @var array List of users.
98
     */
99
    protected $users = [];
100
 
101
    /**
102
     * Send out messages.
103
     * @throws \moodle_exception
104
     */
105
    public function execute() {
106
        global $CFG;
107
 
108
        // Raise the time limit for each discussion.
109
        \core_php_time_limit::raise(120);
110
 
111
        $this->recipient = \core_user::get_user($this->get_userid());
112
 
113
        // Create the generic messageinboundgenerator.
114
        $this->inboundmanager = new \core\message\inbound\address_manager();
115
        $this->inboundmanager->set_handler('\mod_forum\message\inbound\reply_handler');
116
 
117
        $data = $this->get_custom_data();
118
 
119
        $this->prepare_data((array) $data);
120
 
121
        $failedposts = [];
122
        $markposts = [];
123
        $errorcount = 0;
124
        $sentcount = 0;
125
        $this->log_start("Sending messages to {$this->recipient->username} ({$this->recipient->id})");
126
        foreach ($this->courses as $course) {
127
            $coursecontext = \context_course::instance($course->id);
128
            if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
129
                // The course is hidden and the user does not have access to it.
130
                // Permissions may have changed since it was queued.
131
                continue;
132
            }
133
            foreach ($this->courseforums[$course->id] as $forumid) {
134
                $forum = $this->forums[$forumid];
135
 
136
                $cm = get_fast_modinfo($course)->instances['forum'][$forumid];
137
                $modcontext = \context_module::instance($cm->id);
138
 
139
                foreach (array_values($this->forumdiscussions[$forumid]) as $discussionid) {
140
                    $discussion = $this->discussions[$discussionid];
141
 
142
                    if (!forum_user_can_see_discussion($forum, $discussion, $modcontext, $this->recipient)) {
143
                        // User cannot see this discussion.
144
                        // Permissions may have changed since it was queued.
145
                        continue;
146
                    }
147
 
148
                    if (!\mod_forum\subscriptions::is_subscribed($this->recipient->id, $forum, $discussionid, $cm)) {
149
                        // The user does not subscribe to this forum as a whole, or to this specific discussion.
150
                        continue;
151
                    }
152
 
153
                    foreach ($this->posts[$discussionid] as $post) {
154
                        if (!forum_user_can_see_post($forum, $discussion, $post, $this->recipient, $cm)) {
155
                            // User cannot see this post.
156
                            // Permissions may have changed since it was queued.
157
                            continue;
158
                        }
159
 
160
                        if ($this->send_post($course, $forum, $discussion, $post, $cm, $modcontext)) {
161
                            $this->log("Post {$post->id} sent", 1);
162
                            // Mark post as read if forum_usermarksread is set off.
163
                            if (!$CFG->forum_usermarksread) {
164
                                $markposts[$post->id] = true;
165
                            }
166
                            $sentcount++;
167
                        } else {
168
                            $this->log("Failed to send post {$post->id}", 1);
169
                            $failedposts[] = $post->id;
170
                            $errorcount++;
171
                        }
172
                    }
173
                }
174
            }
175
        }
176
 
177
        $this->log_finish("Sent {$sentcount} messages with {$errorcount} failures");
178
        if (!empty($markposts)) {
179
            if (get_user_preferences('forum_markasreadonnotification', 1, $this->recipient->id) == 1) {
180
                $this->log_start("Marking posts as read");
181
                $count = count($markposts);
182
                forum_tp_mark_posts_read($this->recipient, array_keys($markposts));
183
                $this->log_finish("Marked {$count} posts as read");
184
            }
185
        }
186
 
1441 ariadna 187
        if ($errorcount > 0 && $sentcount === 0) {
1 efrain 188
            // All messages errored. So fail.
1441 ariadna 189
            // Checking if the task failed because of empty email address so that it doesn't get rescheduled.
190
            if (!empty($this->recipient->email)) {
191
                throw new \moodle_exception('Error sending posts.');
192
            } else {
193
                mtrace("Failed to send emails for the user with ID ".
194
                    $this->recipient->id ." due to an empty email address. Skipping re-queuing of the task.");
195
            }
1 efrain 196
        } else if ($errorcount > 0) {
197
            // Requeue failed messages as a new task.
198
            $task = new send_user_notifications();
199
            $task->set_userid($this->recipient->id);
200
            $task->set_custom_data($failedposts);
201
            $task->set_component('mod_forum');
202
            $task->set_next_run_time(time() + MINSECS);
203
            $task->set_fail_delay(MINSECS);
204
            \core\task\manager::reschedule_or_queue_adhoc_task($task);
205
        }
206
    }
207
 
208
    /**
209
     * Prepare all data for this run.
210
     *
211
     * Take all post ids, and fetch the relevant authors, discussions, forums, and courses for them.
212
     *
213
     * @param   int[]   $postids The list of post IDs
214
     */
215
    protected function prepare_data(array $postids) {
216
        global $DB;
217
 
218
        if (empty($postids)) {
219
            return;
220
        }
221
 
222
        list($in, $params) = $DB->get_in_or_equal(array_values($postids));
223
        $sql = "SELECT p.*, f.id AS forum, f.course
224
                  FROM {forum_posts} p
225
            INNER JOIN {forum_discussions} d ON d.id = p.discussion
226
            INNER JOIN {forum} f ON f.id = d.forum
227
                 WHERE p.id {$in}";
228
 
229
        $posts = $DB->get_recordset_sql($sql, $params);
230
        $discussionids = [];
231
        $forumids = [];
232
        $courseids = [];
233
        $userids = [];
234
        foreach ($posts as $post) {
235
            $discussionids[] = $post->discussion;
236
            $forumids[] = $post->forum;
237
            $courseids[] = $post->course;
238
            $userids[] = $post->userid;
239
            unset($post->forum);
240
            if (!isset($this->posts[$post->discussion])) {
241
                $this->posts[$post->discussion] = [];
242
            }
243
            $this->posts[$post->discussion][$post->id] = $post;
244
        }
245
        $posts->close();
246
 
247
        if (empty($discussionids)) {
248
            // All posts have been removed since the task was queued.
249
            return;
250
        }
251
 
252
        // Fetch all discussions.
253
        list($in, $params) = $DB->get_in_or_equal(array_values($discussionids));
254
        $this->discussions = $DB->get_records_select('forum_discussions', "id {$in}", $params);
255
        foreach ($this->discussions as $discussion) {
256
            if (empty($this->forumdiscussions[$discussion->forum])) {
257
                $this->forumdiscussions[$discussion->forum] = [];
258
            }
259
            $this->forumdiscussions[$discussion->forum][] = $discussion->id;
260
        }
261
 
262
        // Fetch all forums.
263
        list($in, $params) = $DB->get_in_or_equal(array_values($forumids));
264
        $this->forums = $DB->get_records_select('forum', "id {$in}", $params);
265
        foreach ($this->forums as $forum) {
266
            if (empty($this->courseforums[$forum->course])) {
267
                $this->courseforums[$forum->course] = [];
268
            }
269
            $this->courseforums[$forum->course][] = $forum->id;
270
        }
271
 
272
        // Fetch all courses.
273
        list($in, $params) = $DB->get_in_or_equal(array_values($courseids));
274
        $this->courses = $DB->get_records_select('course', "id $in", $params);
275
 
276
        // Fetch all authors.
277
        list($in, $params) = $DB->get_in_or_equal(array_values($userids));
278
        $users = $DB->get_recordset_select('user', "id $in", $params);
279
        foreach ($users as $user) {
280
            $this->minimise_user_record($user);
281
            $this->users[$user->id] = $user;
282
        }
283
        $users->close();
284
 
285
        // Fill subscription caches for each forum.
286
        // These are per-user.
287
        foreach (array_values($forumids) as $id) {
288
            \mod_forum\subscriptions::fill_subscription_cache($id);
289
            \mod_forum\subscriptions::fill_discussion_subscription_cache($id);
290
        }
291
    }
292
 
293
    /**
294
     * Send the specified post for the current user.
295
     *
296
     * @param   \stdClass   $course
297
     * @param   \stdClass   $forum
298
     * @param   \stdClass   $discussion
299
     * @param   \stdClass   $post
300
     * @param   \stdClass   $cm
301
     * @param   \context    $context
302
     */
303
    protected function send_post($course, $forum, $discussion, $post, $cm, $context) {
304
        global $CFG, $PAGE;
305
 
306
        $author = $this->get_post_author($post->userid, $course, $forum, $cm, $context);
307
        if (empty($author)) {
308
            return false;
309
        }
310
 
311
        // Prepare to actually send the post now, and build up the content.
312
        $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
313
 
314
        $shortname = format_string($course->shortname, true, [
315
                'context' => \context_course::instance($course->id),
316
            ]);
317
 
318
        // Generate a reply-to address from using the Inbound Message handler.
319
        $replyaddress = $this->get_reply_address($course, $forum, $discussion, $post, $cm, $context);
320
 
321
        $data = new \mod_forum\output\forum_post_email(
322
            $course,
323
            $cm,
324
            $forum,
325
            $discussion,
326
            $post,
327
            $author,
328
            $this->recipient,
329
            $this->can_post($course, $forum, $discussion, $post, $cm, $context)
330
        );
331
        $data->viewfullnames = $this->can_view_fullnames($course, $forum, $discussion, $post, $cm, $context);
332
 
333
        // Not all of these variables are used in the default string but are made available to support custom subjects.
334
        $site = get_site();
335
        $a = (object) [
336
            'subject' => $data->get_subject(),
337
            'forumname' => $cleanforumname,
338
            'sitefullname' => format_string($site->fullname),
339
            'siteshortname' => format_string($site->shortname),
340
            'courseidnumber' => $data->get_courseidnumber(),
341
            'coursefullname' => $data->get_coursefullname(),
342
            'courseshortname' => $data->get_coursename(),
343
        ];
344
        $postsubject = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
345
 
346
        // Message headers are stored against the message author.
347
        $author->customheaders = $this->get_message_headers($course, $forum, $discussion, $post, $a, $data);
348
 
349
        $eventdata = new \core\message\message();
350
        $eventdata->courseid            = $course->id;
351
        $eventdata->component           = 'mod_forum';
352
        $eventdata->name                = 'posts';
353
        $eventdata->userfrom            = $author;
354
        $eventdata->userto              = $this->recipient;
355
        $eventdata->subject             = $postsubject;
356
        $eventdata->fullmessage         = $this->get_renderer()->render($data);
357
        $eventdata->fullmessageformat   = FORMAT_PLAIN;
358
        $eventdata->fullmessagehtml     = $this->get_renderer(true)->render($data);
359
        $eventdata->notification        = 1;
360
        $eventdata->replyto             = $replyaddress;
361
        if (!empty($replyaddress)) {
362
            // Add extra text to email messages if they can reply back.
363
            $eventdata->set_additional_content('email', [
364
                    'fullmessage' => [
365
                        'footer' => "\n\n" . get_string('replytopostbyemail', 'mod_forum'),
366
                    ],
367
                    'fullmessagehtml' => [
368
                        'footer' => \html_writer::tag('p', get_string('replytopostbyemail', 'mod_forum')),
369
                    ]
370
                ]);
371
        }
372
 
373
        $eventdata->smallmessage = get_string('smallmessage', 'forum', (object) [
374
                'user' => fullname($author),
375
                'forumname' => "$shortname: " . format_string($forum->name, true) . ": " . $discussion->name,
376
                'message' => $post->message,
377
            ]);
378
 
379
        $contexturl = new \moodle_url('/mod/forum/discuss.php', ['d' => $discussion->id], "p{$post->id}");
380
        $eventdata->contexturl = $contexturl->out();
381
        $eventdata->contexturlname = $discussion->name;
382
        // User image.
383
        $userpicture = new \user_picture($author);
384
        $userpicture->size = 1; // Use f1 size.
385
        $userpicture->includetoken = $this->recipient->id; // Generate an out-of-session token for the user receiving the message.
386
        $eventdata->customdata = [
387
            'cmid' => $cm->id,
388
            'instance' => $forum->id,
389
            'discussionid' => $discussion->id,
390
            'postid' => $post->id,
391
            'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
392
            'actionbuttons' => [
393
                'reply' => get_string_manager()->get_string('reply', 'forum', null, $eventdata->userto->lang),
394
            ],
395
        ];
396
 
397
        return message_send($eventdata);
398
    }
399
 
400
    /**
401
     * Fetch and initialise the post author.
402
     *
403
     * @param   int         $userid The id of the user to fetch
404
     * @param   \stdClass   $course
405
     * @param   \stdClass   $forum
406
     * @param   \stdClass   $cm
407
     * @param   \context    $context
408
     * @return  \stdClass
409
     */
410
    protected function get_post_author($userid, $course, $forum, $cm, $context) {
411
        if (!isset($this->users[$userid])) {
412
            // This user no longer exists.
413
            return false;
414
        }
415
 
416
        $user = $this->users[$userid];
417
 
418
        if (!isset($user->groups)) {
419
            // Initialise the groups list.
420
            $user->groups = [];
421
        }
422
 
423
        if (!isset($user->groups[$forum->id])) {
424
            $user->groups[$forum->id] = groups_get_all_groups($course->id, $user->id, $cm->groupingid);
425
        }
426
 
427
        // Clone the user object to prevent leaks between messages.
428
        return (object) (array) $user;
429
    }
430
 
431
    /**
432
     * Helper to fetch the required renderer, instantiating as required.
433
     *
434
     * @param   bool    $html Whether to fetch the HTML renderer
435
     * @return  \core_renderer
436
     */
437
    protected function get_renderer($html = false) {
438
        global $PAGE;
439
 
440
        $target = $html ? 'htmlemail' : 'textemail';
441
 
442
        if (!isset($this->renderers[$target])) {
443
            $this->renderers[$target] = $PAGE->get_renderer('mod_forum', 'email', $target);
444
        }
445
 
446
        return $this->renderers[$target];
447
    }
448
 
449
    /**
450
     * Get the list of message headers.
451
     *
452
     * @param   \stdClass   $course
453
     * @param   \stdClass   $forum
454
     * @param   \stdClass   $discussion
455
     * @param   \stdClass   $post
456
     * @param   \stdClass   $a The list of strings for this  post
457
     * @param   \core\message\message $message The message to be sent
458
     * @return  \stdClass
459
     */
460
    protected function get_message_headers($course, $forum, $discussion, $post, $a, $message) {
461
        $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
462
        $viewurl = new \moodle_url('/mod/forum/view.php', ['f' => $forum->id]);
463
 
464
        $headers = [
465
            // Headers to make emails easier to track.
466
            'List-Id: "' . $cleanforumname . '" ' . generate_email_messageid('moodleforum' . $forum->id),
467
            'List-Help: ' . $viewurl->out(),
468
            'Message-ID: ' . forum_get_email_message_id($post->id, $this->recipient->id),
469
            'X-Course-Id: ' . $course->id,
470
            'X-Course-Name: '. format_string($course->fullname, true),
471
 
472
            // Headers to help prevent auto-responders.
473
            'Precedence: Bulk',
474
            'X-Auto-Response-Suppress: All',
475
            'Auto-Submitted: auto-generated',
476
            'List-Unsubscribe: <' . $message->get_unsubscribediscussionlink() . '>',
477
        ];
478
 
479
        $rootid = forum_get_email_message_id($discussion->firstpost, $this->recipient->id);
480
 
481
        if ($post->parent) {
482
            // This post is a reply, so add reply header (RFC 2822).
483
            $parentid = forum_get_email_message_id($post->parent, $this->recipient->id);
484
            $headers[] = "In-Reply-To: $parentid";
485
 
486
            // If the post is deeply nested we also reference the parent message id and
487
            // the root message id (if different) to aid threading when parts of the email
488
            // conversation have been deleted (RFC1036).
489
            if ($post->parent != $discussion->firstpost) {
490
                $headers[] = "References: $rootid $parentid";
491
            } else {
492
                $headers[] = "References: $parentid";
493
            }
494
        } else {
495
            // If the message IDs that Moodle creates are overwritten then referencing these
496
            // IDs here will enable then to still thread correctly with the first email.
497
            $headers[] = "In-Reply-To: $rootid";
498
            $headers[] = "References: $rootid";
499
        }
500
 
501
        // MS Outlook / Office uses poorly documented and non standard headers, including
502
        // Thread-Topic which overrides the Subject and shouldn't contain Re: or Fwd: etc.
503
        $aclone = (object) (array) $a;
504
        $aclone->subject = $discussion->name;
505
        $threadtopic = html_to_text(get_string('postmailsubject', 'forum', $aclone), 0);
506
        $headers[] = "Thread-Topic: $threadtopic";
507
        $headers[] = "Thread-Index: " . substr($rootid, 1, 28);
508
 
509
        return $headers;
510
    }
511
 
512
    /**
513
     * Get a no-reply address for this user to reply to the current post.
514
     *
515
     * @param   \stdClass   $course
516
     * @param   \stdClass   $forum
517
     * @param   \stdClass   $discussion
518
     * @param   \stdClass   $post
519
     * @param   \stdClass   $cm
520
     * @param   \context    $context
521
     * @return  string
522
     */
523
    protected function get_reply_address($course, $forum, $discussion, $post, $cm, $context) {
524
        if ($this->can_post($course, $forum, $discussion, $post, $cm, $context)) {
525
            // Generate a reply-to address from using the Inbound Message handler.
526
            $this->inboundmanager->set_data($post->id);
527
            return $this->inboundmanager->generate($this->recipient->id);
528
        }
529
 
530
        // TODO Check if we can return a string.
531
        // This will be controlled by the event.
532
        return null;
533
    }
534
 
535
    /**
536
     * Check whether the user can post.
537
     *
538
     * @param   \stdClass   $course
539
     * @param   \stdClass   $forum
540
     * @param   \stdClass   $discussion
541
     * @param   \stdClass   $post
542
     * @param   \stdClass   $cm
543
     * @param   \context    $context
544
     * @return  bool
545
     */
546
    protected function can_post($course, $forum, $discussion, $post, $cm, $context) {
547
        if (!isset($this->canpostto[$discussion->id])) {
548
            $this->canpostto[$discussion->id] = forum_user_can_post($forum, $discussion, $this->recipient, $cm, $course, $context);
549
        }
550
        return $this->canpostto[$discussion->id];
551
    }
552
 
553
    /**
554
     * Check whether the user can view full names of other users.
555
     *
556
     * @param   \stdClass   $course
557
     * @param   \stdClass   $forum
558
     * @param   \stdClass   $discussion
559
     * @param   \stdClass   $post
560
     * @param   \stdClass   $cm
561
     * @param   \context    $context
562
     * @return  bool
563
     */
564
    protected function can_view_fullnames($course, $forum, $discussion, $post, $cm, $context) {
565
        if (!isset($this->viewfullnames[$forum->id])) {
566
            $this->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $context, $this->recipient->id);
567
        }
568
 
569
        return $this->viewfullnames[$forum->id];
570
    }
571
 
572
    /**
573
     * Removes properties from user record that are not necessary for sending post notifications.
574
     *
575
     * @param   \stdClass   $user
576
     */
577
    protected function minimise_user_record(\stdClass $user) {
578
        // We store large amount of users in one huge array, make sure we do not store info there we do not actually
579
        // need in mail generation code or messaging.
580
        unset($user->institution);
581
        unset($user->department);
582
        unset($user->address);
583
        unset($user->city);
584
        unset($user->currentlogin);
585
        unset($user->description);
586
        unset($user->descriptionformat);
587
    }
588
}