first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+546
View File
@@ -0,0 +1,546 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* A scheduled task for forum cron.
*
* @package mod_forum
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_forum\task;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/mod/forum/lib.php');
/**
* The main scheduled task for the forum.
*
* @package mod_forum
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cron_task extends \core\task\scheduled_task {
// Use the logging trait to get some nice, juicy, logging.
use \core\task\logging_trait;
/**
* @var The list of courses which contain posts to be sent.
*/
protected $courses = [];
/**
* @var The list of forums which contain posts to be sent.
*/
protected $forums = [];
/**
* @var The list of discussions which contain posts to be sent.
*/
protected $discussions = [];
/**
* @var The list of posts to be sent.
*/
protected $posts = [];
/**
* @var The list of post authors.
*/
protected $users = [];
/**
* @var The list of subscribed users.
*/
protected $subscribedusers = [];
/**
* @var The list of digest users.
*/
protected $digestusers = [];
/**
* @var The list of adhoc data for sending.
*/
protected $adhocdata = [];
/**
* Get a descriptive name for this task (shown to admins).
*
* @return string
*/
public function get_name() {
return get_string('crontask', 'mod_forum');
}
/**
* Execute the scheduled task.
*/
public function execute() {
global $CFG, $DB;
$timenow = time();
// Delete any really old posts in the digest queue.
$weekago = $timenow - (7 * 24 * 3600);
$this->log_start("Removing old digest records from 7 days ago.");
$DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
$this->log_finish("Removed all old digest records.");
$endtime = $timenow - $CFG->maxeditingtime;
$starttime = $endtime - (2 * DAYSECS);
$this->log_start("Fetching unmailed posts.");
if (!$posts = $this->get_unmailed_posts($starttime, $endtime, $timenow)) {
$this->log_finish("No posts found.", 1);
return false;
}
$this->log_finish("Done");
// Process post data and turn into adhoc tasks.
$this->process_post_data($posts);
// Mark posts as read.
list($in, $params) = $DB->get_in_or_equal(array_keys($posts));
$DB->set_field_select('forum_posts', 'mailed', 1, "id {$in}", $params);
}
/**
* Process all posts and convert to appropriated hoc tasks.
*
* @param \stdClass[] $posts
*/
protected function process_post_data($posts) {
$discussionids = [];
$forumids = [];
$courseids = [];
$this->log_start("Processing post information");
$start = microtime(true);
foreach ($posts as $id => $post) {
$discussionids[$post->discussion] = true;
$forumids[$post->forum] = true;
$courseids[$post->course] = true;
$this->add_data_for_post($post);
$this->posts[$id] = $post;
}
$this->log_finish(sprintf("Processed %s posts", count($this->posts)));
if (empty($this->posts)) {
$this->log("No posts found. Returning early.");
return;
}
// Please note, this order is intentional.
// The forum cache makes use of the course.
$this->log_start("Filling caches");
$start = microtime(true);
$this->log_start("Filling course cache", 1);
$this->fill_course_cache(array_keys($courseids));
$this->log_finish("Done", 1);
$this->log_start("Filling forum cache", 1);
$this->fill_forum_cache(array_keys($forumids));
$this->log_finish("Done", 1);
$this->log_start("Filling discussion cache", 1);
$this->fill_discussion_cache(array_keys($discussionids));
$this->log_finish("Done", 1);
$this->log_start("Filling user subscription cache", 1);
$this->fill_user_subscription_cache();
$this->log_finish("Done", 1);
$this->log_start("Filling digest cache", 1);
$this->fill_digest_cache();
$this->log_finish("Done", 1);
$this->log_finish("All caches filled");
$this->log_start("Queueing user tasks.");
$this->queue_user_tasks();
$this->log_finish("All tasks queued.");
}
/**
* Fill the course cache.
*
* @param int[] $courseids
*/
protected function fill_course_cache($courseids) {
global $DB;
list($in, $params) = $DB->get_in_or_equal($courseids);
$this->courses = $DB->get_records_select('course', "id $in", $params);
}
/**
* Fill the forum cache.
*
* @param int[] $forumids
*/
protected function fill_forum_cache($forumids) {
global $DB;
$requiredfields = [
'id',
'course',
'forcesubscribe',
'type',
];
list($in, $params) = $DB->get_in_or_equal($forumids);
$this->forums = $DB->get_records_select('forum', "id $in", $params, '', implode(', ', $requiredfields));
foreach ($this->forums as $id => $forum) {
\mod_forum\subscriptions::fill_subscription_cache($id);
\mod_forum\subscriptions::fill_discussion_subscription_cache($id);
}
}
/**
* Fill the discussion cache.
*
* @param int[] $discussionids
*/
protected function fill_discussion_cache($discussionids) {
global $DB;
if (empty($discussionids)) {
$this->discussions = [];
} else {
$requiredfields = [
'id',
'groupid',
'firstpost',
'timestart',
'timeend',
];
list($in, $params) = $DB->get_in_or_equal($discussionids);
$this->discussions = $DB->get_records_select(
'forum_discussions', "id $in", $params, '', implode(', ', $requiredfields));
}
}
/**
* Fill the cache of user digest preferences.
*/
protected function fill_digest_cache() {
global $DB;
if (empty($this->users)) {
return;
}
// Get the list of forum subscriptions for per-user per-forum maildigest settings.
list($in, $params) = $DB->get_in_or_equal(array_keys($this->users));
$digestspreferences = $DB->get_recordset_select(
'forum_digests', "userid $in", $params, '', 'id, userid, forum, maildigest');
foreach ($digestspreferences as $digestpreference) {
if (!isset($this->digestusers[$digestpreference->forum])) {
$this->digestusers[$digestpreference->forum] = [];
}
$this->digestusers[$digestpreference->forum][$digestpreference->userid] = $digestpreference->maildigest;
}
$digestspreferences->close();
}
/**
* Add dsta for the current forum post to the structure of adhoc data.
*
* @param \stdClass $post
*/
protected function add_data_for_post($post) {
if (!isset($this->adhocdata[$post->course])) {
$this->adhocdata[$post->course] = [];
}
if (!isset($this->adhocdata[$post->course][$post->forum])) {
$this->adhocdata[$post->course][$post->forum] = [];
}
if (!isset($this->adhocdata[$post->course][$post->forum][$post->discussion])) {
$this->adhocdata[$post->course][$post->forum][$post->discussion] = [];
}
$this->adhocdata[$post->course][$post->forum][$post->discussion][$post->id] = $post->id;
}
/**
* Fill the cache of user subscriptions.
*/
protected function fill_user_subscription_cache() {
foreach ($this->forums as $forum) {
$cm = get_fast_modinfo($this->courses[$forum->course])->instances['forum'][$forum->id];
$modcontext = \context_module::instance($cm->id);
$this->subscribedusers[$forum->id] = [];
if ($users = \mod_forum\subscriptions::fetch_subscribed_users($forum, 0, $modcontext, 'u.id, u.maildigest', true)) {
foreach ($users as $user) {
// This user is subscribed to this forum.
$this->subscribedusers[$forum->id][$user->id] = $user->id;
if (!isset($this->users[$user->id])) {
// Store minimal user info.
$this->users[$user->id] = $user;
}
}
// Release memory.
unset($users);
}
}
}
/**
* Queue the user tasks.
*/
protected function queue_user_tasks() {
global $CFG, $DB;
$timenow = time();
$sitetimezone = \core_date::get_server_timezone();
$counts = [
'digests' => 0,
'individuals' => 0,
'users' => 0,
'ignored' => 0,
'messages' => 0,
];
$this->log("Processing " . count($this->users) . " users", 1);
foreach ($this->users as $user) {
$usercounts = [
'digests' => 0,
'messages' => 0,
];
$send = false;
// Setup this user so that the capabilities are cached, and environment matches receiving user.
\core\cron::setup_user($user);
list($individualpostdata, $digestpostdata) = $this->fetch_posts_for_user($user);
if (!empty($digestpostdata)) {
// Insert all of the records for the digest.
$DB->insert_records('forum_queue', $digestpostdata);
$servermidnight = usergetmidnight($timenow, $sitetimezone);
$digesttime = $servermidnight + ($CFG->digestmailtime * 3600);
if ($digesttime < $timenow) {
// Digest time is in the past. Get a new time for tomorrow.
$servermidnight = usergetmidnight($timenow + DAYSECS, $sitetimezone);
$digesttime = $servermidnight + ($CFG->digestmailtime * 3600);
}
$task = new \mod_forum\task\send_user_digests();
$task->set_userid($user->id);
$task->set_component('mod_forum');
$task->set_custom_data(['servermidnight' => $servermidnight]);
$task->set_next_run_time($digesttime);
\core\task\manager::reschedule_or_queue_adhoc_task($task);
$usercounts['digests']++;
$send = true;
}
if (!empty($individualpostdata)) {
$usercounts['messages'] += count($individualpostdata);
$task = new \mod_forum\task\send_user_notifications();
$task->set_userid($user->id);
$task->set_custom_data($individualpostdata);
$task->set_component('mod_forum');
\core\task\manager::queue_adhoc_task($task);
$counts['individuals']++;
$send = true;
}
if ($send) {
$counts['users']++;
$counts['messages'] += $usercounts['messages'];
$counts['digests'] += $usercounts['digests'];
} else {
$counts['ignored']++;
}
$this->log(sprintf("Queued %d digests and %d messages for %s",
$usercounts['digests'],
$usercounts['messages'],
$user->id
), 2);
}
$this->log(
sprintf(
"Queued %d digests, and %d individual tasks for %d post mails. " .
"Unique users: %d (%d ignored)",
$counts['digests'],
$counts['individuals'],
$counts['messages'],
$counts['users'],
$counts['ignored']
), 1);
}
/**
* Fetch posts for this user.
*
* @param \stdClass $user The user to fetch posts for.
*/
protected function fetch_posts_for_user($user) {
// We maintain a mapping of user groups for each forum.
$usergroups = [];
$digeststructure = [];
$poststructure = $this->adhocdata;
$poststosend = [];
foreach ($poststructure as $courseid => $forumids) {
$course = $this->courses[$courseid];
foreach ($forumids as $forumid => $discussionids) {
$forum = $this->forums[$forumid];
$maildigest = forum_get_user_maildigest_bulk($this->digestusers, $user, $forumid);
if (!isset($this->subscribedusers[$forumid][$user->id])) {
// This user has no subscription of any kind to this forum.
// Do not send them any posts at all.
unset($poststructure[$courseid][$forumid]);
continue;
}
$subscriptiontime = \mod_forum\subscriptions::fetch_discussion_subscription($forum->id, $user->id);
$cm = get_fast_modinfo($course)->instances['forum'][$forumid];
foreach ($discussionids as $discussionid => $postids) {
$discussion = $this->discussions[$discussionid];
if (!\mod_forum\subscriptions::is_subscribed($user->id, $forum, $discussionid, $cm)) {
// The user does not subscribe to this forum as a whole, or to this specific discussion.
unset($poststructure[$courseid][$forumid][$discussionid]);
continue;
}
if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
// This discussion has a groupmode set (SEPARATEGROUPS or VISIBLEGROUPS).
// Check whether the user can view it based on their groups.
if (!isset($usergroups[$forum->id])) {
$usergroups[$forum->id] = groups_get_all_groups($courseid, $user->id, $cm->groupingid);
}
if (!isset($usergroups[$forum->id][$discussion->groupid])) {
// This user is not a member of this group, or the group no longer exists.
$modcontext = \context_module::instance($cm->id);
if (!has_capability('moodle/site:accessallgroups', $modcontext, $user)) {
// This user does not have the accessallgroups and is not a member of the group.
// Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
unset($poststructure[$courseid][$forumid][$discussionid]);
continue;
}
}
}
foreach ($postids as $postid) {
$post = $this->posts[$postid];
if ($subscriptiontime) {
// Skip posts if the user subscribed to the discussion after it was created.
$subscribedafter = isset($subscriptiontime[$post->discussion]);
$subscribedafter = $subscribedafter && ($subscriptiontime[$post->discussion] > $post->created);
if ($subscribedafter) {
// The user subscribed to the discussion/forum after this post was created.
unset($poststructure[$courseid][$forumid][$discussionid][$postid]);
continue;
}
}
if ($maildigest > 0) {
// This user wants the mails to be in digest form.
$digeststructure[] = (object) [
'userid' => $user->id,
'discussionid' => $discussion->id,
'postid' => $post->id,
'timemodified' => $post->created,
];
unset($poststructure[$courseid][$forumid][$discussionid][$postid]);
continue;
} else {
// Add this post to the list of postids to be sent.
$poststosend[] = $postid;
}
}
}
if (empty($poststructure[$courseid][$forumid])) {
// This user is not subscribed to any discussions in this forum at all.
unset($poststructure[$courseid][$forumid]);
continue;
}
}
if (empty($poststructure[$courseid])) {
// This user is not subscribed to any forums in this course.
unset($poststructure[$courseid]);
}
}
return [$poststosend, $digeststructure];
}
/**
* Returns a list of all new posts that have not been mailed yet
*
* @param int $starttime posts created after this time
* @param int $endtime posts created before this
* @param int $now used for timed discussions only
* @return array
*/
protected function get_unmailed_posts($starttime, $endtime, $now = null) {
global $CFG, $DB;
$params = array();
$params['mailed'] = FORUM_MAILED_PENDING;
$params['ptimestart'] = $starttime;
$params['ptimeend'] = $endtime;
$params['mailnow'] = 1;
if (!empty($CFG->forum_enabletimedposts)) {
if (empty($now)) {
$now = time();
}
$selectsql = "AND (p.created >= :ptimestart OR d.timestart >= :pptimestart)";
$params['pptimestart'] = $starttime;
$timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
$params['dtimestart'] = $now;
$params['dtimeend'] = $now;
} else {
$timedsql = "";
$selectsql = "AND p.created >= :ptimestart";
}
return $DB->get_records_sql(
"SELECT
p.id,
p.discussion,
d.forum,
d.course,
p.created,
p.parent,
p.userid
FROM {forum_posts} p
JOIN {forum_discussions} d ON d.id = p.discussion
WHERE p.mailed = :mailed
$selectsql
AND (p.created < :ptimeend OR p.mailnow = :mailnow)
$timedsql
ORDER BY p.modified ASC",
$params);
}
}
@@ -0,0 +1,620 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file defines an adhoc task to send notifications.
*
* @package mod_forum
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_forum\task;
defined('MOODLE_INTERNAL') || die();
use html_writer;
require_once($CFG->dirroot . '/mod/forum/lib.php');
/**
* Adhoc task to send moodle forum digests for the specified user.
*
* @package mod_forum
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class send_user_digests extends \core\task\adhoc_task {
// Use the logging trait to get some nice, juicy, logging.
use \core\task\logging_trait;
/**
* @var \stdClass A shortcut to $USER.
*/
protected $recipient;
/**
* @var bool[] Whether the user can view fullnames for each forum.
*/
protected $viewfullnames = [];
/**
* @var bool[] Whether the user can post in each forum.
*/
protected $canpostto = [];
/**
* @var \stdClass[] Courses with posts them.
*/
protected $courses = [];
/**
* @var \stdClass[] Forums with posts them.
*/
protected $forums = [];
/**
* @var \stdClass[] Discussions with posts them.
*/
protected $discussions = [];
/**
* @var \stdClass[] The posts to be sent.
*/
protected $posts = [];
/**
* @var \stdClass[] The various authors.
*/
protected $users = [];
/**
* @var \stdClass[] A list of any per-forum digest preference that this user holds.
*/
protected $forumdigesttypes = [];
/**
* @var bool Whether the user has requested HTML or not.
*/
protected $allowhtml = true;
/**
* @var string The subject of the message.
*/
protected $postsubject = '';
/**
* @var string The plaintext content of the whole message.
*/
protected $notificationtext = '';
/**
* @var string The HTML content of the whole message.
*/
protected $notificationhtml = '';
/**
* @var string The plaintext content for the current discussion being processed.
*/
protected $discussiontext = '';
/**
* @var string The HTML content for the current discussion being processed.
*/
protected $discussionhtml = '';
/**
* @var int The number of messages sent in this digest.
*/
protected $sentcount = 0;
/**
* @var \renderer[][] A cache of the different types of renderer, stored both by target (HTML, or Text), and type.
*/
protected $renderers = [
'html' => [],
'text' => [],
];
/**
* @var int[] A list of post IDs to be marked as read for this user.
*/
protected $markpostsasread = [];
/**
* Send out messages.
* @throws \moodle_exception
*/
public function execute() {
$starttime = time();
$this->recipient = \core_user::get_user($this->get_userid());
$this->log_start("Sending forum digests for {$this->recipient->username} ({$this->recipient->id})");
if (empty($this->recipient->mailformat) || $this->recipient->mailformat != 1) {
// This user does not want to receive HTML.
$this->allowhtml = false;
}
// Fetch all of the data we need to mail these posts.
$this->prepare_data($starttime);
if (empty($this->posts) || empty($this->discussions) || empty($this->forums)) {
$this->log_finish("No messages found to send.");
return;
}
// Add the message headers.
$this->add_message_header();
foreach ($this->discussions as $discussion) {
// Raise the time limit for each discussion.
\core_php_time_limit::raise(120);
// Grab the data pertaining to this discussion.
$forum = $this->forums[$discussion->forum];
$course = $this->courses[$forum->course];
$cm = get_fast_modinfo($course)->instances['forum'][$forum->id];
$modcontext = \context_module::instance($cm->id);
$coursecontext = \context_course::instance($course->id);
if (empty($this->posts[$discussion->id])) {
// Somehow there are no posts.
// This should not happen but better safe than sorry.
continue;
}
if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
// The course is hidden and the user does not have access to it.
// Permissions may have changed since it was queued.
continue;
}
if (!forum_user_can_see_discussion($forum, $discussion, $modcontext, $this->recipient)) {
// User cannot see this discussion.
// Permissions may have changed since it was queued.
continue;
}
if (!\mod_forum\subscriptions::is_subscribed($this->recipient->id, $forum, $discussion->id, $cm)) {
// The user does not subscribe to this forum as a whole, or to this specific discussion.
continue;
}
// Fetch additional values relating to this forum.
if (!isset($this->canpostto[$discussion->id])) {
$this->canpostto[$discussion->id] = forum_user_can_post(
$forum, $discussion, $this->recipient, $cm, $course, $modcontext);
}
if (!isset($this->viewfullnames[$forum->id])) {
$this->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext, $this->recipient->id);
}
// Set the discussion storage values.
$discussionpostcount = 0;
$this->discussiontext = '';
$this->discussionhtml = '';
// Add the header for this discussion.
$this->add_discussion_header($discussion, $forum, $course);
$this->log_start("Adding messages in discussion {$discussion->id} (forum {$forum->id})", 1);
// Add all posts in this forum.
foreach ($this->posts[$discussion->id] as $post) {
$author = $this->get_post_author($post->userid, $course, $forum, $cm, $modcontext);
if (empty($author)) {
// Unable to find the author. Skip to avoid errors.
continue;
}
if (!forum_user_can_see_post($forum, $discussion, $post, $this->recipient, $cm)) {
// User cannot see this post.
// Permissions may have changed since it was queued.
continue;
}
$this->add_post_body($author, $post, $discussion, $forum, $cm, $course);
$discussionpostcount++;
}
// Add the forum footer.
$this->add_discussion_footer($discussion, $forum, $course);
// Add the data for this discussion to the notification body.
if ($discussionpostcount) {
$this->sentcount += $discussionpostcount;
$this->notificationtext .= $this->discussiontext;
$this->notificationhtml .= $this->discussionhtml;
$this->log_finish("Added {$discussionpostcount} messages to discussion {$discussion->id}", 1);
} else {
$this->log_finish("No messages found in discussion {$discussion->id} - skipped.", 1);
}
}
if ($this->sentcount) {
// This digest has at least one post and should therefore be sent.
if ($this->send_mail()) {
$this->log_finish("Digest sent with {$this->sentcount} messages.");
if (get_user_preferences('forum_markasreadonnotification', 1, $this->recipient->id) == 1) {
forum_tp_mark_posts_read($this->recipient, $this->markpostsasread);
}
} else {
$this->log_finish("Issue sending digest. Skipping.");
throw new \moodle_exception("Issue sending digest. Skipping.");
}
} else {
$this->log_finish("No messages found to send.");
}
// Empty the queue only if successful.
$this->empty_queue($this->recipient->id, $starttime);
// We have finishied all digest emails, update $CFG->digestmailtimelast.
set_config('digestmailtimelast', $starttime);
}
/**
* Prepare the data for this run.
*
* Note: This will also remove posts from the queue.
*
* @param int $timenow
*/
protected function prepare_data(int $timenow) {
global $DB;
$sql = "SELECT p.*, f.id AS forum, f.course
FROM {forum_queue} q
INNER JOIN {forum_posts} p ON p.id = q.postid
INNER JOIN {forum_discussions} d ON d.id = p.discussion
INNER JOIN {forum} f ON f.id = d.forum
WHERE q.userid = :userid
AND q.timemodified < :timemodified
ORDER BY d.id, q.timemodified ASC";
$queueparams = [
'userid' => $this->recipient->id,
'timemodified' => $timenow,
];
$posts = $DB->get_recordset_sql($sql, $queueparams);
$discussionids = [];
$forumids = [];
$courseids = [];
$userids = [];
foreach ($posts as $post) {
$discussionids[] = $post->discussion;
$forumids[] = $post->forum;
$courseids[] = $post->course;
$userids[] = $post->userid;
unset($post->forum);
if (!isset($this->posts[$post->discussion])) {
$this->posts[$post->discussion] = [];
}
$this->posts[$post->discussion][$post->id] = $post;
}
$posts->close();
if (empty($discussionids)) {
// All posts have been removed since the task was queued.
$this->empty_queue($this->recipient->id, $timenow);
return;
}
list($in, $params) = $DB->get_in_or_equal($discussionids);
$this->discussions = $DB->get_records_select('forum_discussions', "id {$in}", $params);
list($in, $params) = $DB->get_in_or_equal($forumids);
$this->forums = $DB->get_records_select('forum', "id {$in}", $params);
list($in, $params) = $DB->get_in_or_equal($courseids);
$this->courses = $DB->get_records_select('course', "id $in", $params);
list($in, $params) = $DB->get_in_or_equal($userids);
$this->users = $DB->get_records_select('user', "id $in", $params);
$this->fill_digest_cache();
}
/**
* Empty the queue of posts for this user.
*
* @param int $userid user id which queue elements are going to be removed.
* @param int $timemodified up time limit of the queue elements to be removed.
*/
protected function empty_queue(int $userid, int $timemodified): void {
global $DB;
$DB->delete_records_select('forum_queue', "userid = :userid AND timemodified < :timemodified", [
'userid' => $userid,
'timemodified' => $timemodified,
]);
}
/**
* Fill the cron digest cache.
*/
protected function fill_digest_cache() {
global $DB;
$this->forumdigesttypes = $DB->get_records_menu('forum_digests', [
'userid' => $this->recipient->id,
], '', 'forum, maildigest');
}
/**
* Fetch and initialise the post author.
*
* @param int $userid The id of the user to fetch
* @param \stdClass $course
* @param \stdClass $forum
* @param \stdClass $cm
* @param \context $context
* @return \stdClass
*/
protected function get_post_author($userid, $course, $forum, $cm, $context) {
if (!isset($this->users[$userid])) {
// This user no longer exists.
return false;
}
$user = $this->users[$userid];
if (!isset($user->groups)) {
// Initialise the groups list.
$user->groups = [];
}
if (!isset($user->groups[$forum->id])) {
$user->groups[$forum->id] = groups_get_all_groups($course->id, $user->id, $cm->groupingid);
}
// Clone the user object to prevent leaks between messages.
return (object) (array) $user;
}
/**
* Add the header to this message.
*/
protected function add_message_header() {
$site = get_site();
// Set the subject of the message.
$this->postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
// And the content of the header in body.
$headerdata = (object) [
'sitename' => format_string($site->fullname, true),
'userprefs' => (new \moodle_url('/user/forum.php', [
'id' => $this->recipient->id,
'course' => $site->id,
]))->out(false),
];
$this->notificationtext .= get_string('digestmailheader', 'forum', $headerdata) . "\n";
if ($this->allowhtml) {
$headerdata->userprefs = html_writer::link($headerdata->userprefs, get_string('digestmailprefs', 'forum'), [
'target' => '_blank',
]);
$this->notificationhtml .= html_writer::tag('p', get_string('digestmailheader', 'forum', $headerdata));
$this->notificationhtml .= html_writer::empty_tag('br');
$this->notificationhtml .= html_writer::empty_tag('hr', [
'size' => 1,
'noshade' => 'noshade',
]);
}
}
/**
* Add the header for this discussion.
*
* @param \stdClass $discussion The discussion to add the footer for
* @param \stdClass $forum The forum that the discussion belongs to
* @param \stdClass $course The course that the forum belongs to
*/
protected function add_discussion_header($discussion, $forum, $course) {
global $CFG;
$shortname = format_string($course->shortname, true, [
'context' => \context_course::instance($course->id),
]);
$strforums = get_string('forums', 'forum');
$this->discussiontext .= "\n=====================================================================\n\n";
$this->discussiontext .= "$shortname -> $strforums -> " . format_string($forum->name, true);
if ($discussion->name != $forum->name) {
$this->discussiontext .= " -> " . format_string($discussion->name, true);
}
$this->discussiontext .= "\n";
$this->discussiontext .= new \moodle_url('/mod/forum/discuss.php', [
'd' => $discussion->id,
]);
$this->discussiontext .= "\n";
if ($this->allowhtml) {
$this->discussionhtml .= "<p><font face=\"sans-serif\">".
"<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
"<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
"<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">" .
format_string($forum->name, true)."</a>";
if ($discussion->name == $forum->name) {
$this->discussionhtml .= "</font></p>";
} else {
$this->discussionhtml .=
" -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">" .
format_string($discussion->name, true)."</a></font></p>";
}
$this->discussionhtml .= '<p>';
}
}
/**
* Add the body of this post.
*
* @param \stdClass $author The author of the post
* @param \stdClass $post The post being sent
* @param \stdClass $discussion The discussion that the post is in
* @param \stdClass $forum The forum that the discussion belongs to
* @param \cminfo $cm The cminfo object for the forum
* @param \stdClass $course The course that the forum belongs to
*/
protected function add_post_body($author, $post, $discussion, $forum, $cm, $course) {
global $CFG;
$canreply = $this->canpostto[$discussion->id];
$data = new \mod_forum\output\forum_post_email(
$course,
$cm,
$forum,
$discussion,
$post,
$author,
$this->recipient,
$canreply
);
// Override the viewfullnames value.
$data->viewfullnames = $this->viewfullnames[$forum->id];
// Determine the type of digest being sent.
$maildigest = $this->get_maildigest($forum->id);
$textrenderer = $this->get_renderer($maildigest);
$this->discussiontext .= $textrenderer->render($data);
$this->discussiontext .= "\n";
if ($this->allowhtml) {
$htmlrenderer = $this->get_renderer($maildigest, true);
$this->discussionhtml .= $htmlrenderer->render($data);
$this->log("Adding post {$post->id} in format {$maildigest} with HTML", 2);
} else {
$this->log("Adding post {$post->id} in format {$maildigest} without HTML", 2);
}
if ($maildigest == 1 && !$CFG->forum_usermarksread) {
// Create an array of postid's for this user to mark as read.
$this->markpostsasread[] = $post->id;
}
}
/**
* Add the footer for this discussion.
*
* @param \stdClass $discussion The discussion to add the footer for
*/
protected function add_discussion_footer($discussion) {
global $CFG;
if ($this->allowhtml) {
$footerlinks = [];
$forum = $this->forums[$discussion->forum];
if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
// This forum is force subscribed. The user cannot unsubscribe.
$footerlinks[] = get_string("everyoneissubscribed", "forum");
} else {
$footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" .
get_string("unsubscribe", "forum") . "</a>";
}
$footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" .
get_string("digestmailpost", "forum") . '</a>';
$this->discussionhtml .= "\n<div class='mdl-right'><font size=\"1\">" .
implode('&nbsp;', $footerlinks) . '</font></div>';
$this->discussionhtml .= '<hr size="1" noshade="noshade" /></p>';
}
}
/**
* Get the forum digest type for the specified forum, failing back to
* the default setting for the current user if not specified.
*
* @param int $forumid
* @return int
*/
protected function get_maildigest($forumid) {
$maildigest = -1;
if (isset($this->forumdigesttypes[$forumid])) {
$maildigest = $this->forumdigesttypes[$forumid];
}
if ($maildigest === -1 && !empty($this->recipient->maildigest)) {
$maildigest = $this->recipient->maildigest;
}
if ($maildigest === -1) {
// There is no maildigest type right now.
$maildigest = 1;
}
return $maildigest;
}
/**
* Send the composed message to the user.
*/
protected function send_mail() {
// Headers to help prevent auto-responders.
$userfrom = \core_user::get_noreply_user();
$userfrom->customheaders = array(
"Precedence: Bulk",
'X-Auto-Response-Suppress: All',
'Auto-Submitted: auto-generated',
);
$eventdata = new \core\message\message();
$eventdata->courseid = SITEID;
$eventdata->component = 'mod_forum';
$eventdata->name = 'digests';
$eventdata->userfrom = $userfrom;
$eventdata->userto = $this->recipient;
$eventdata->subject = $this->postsubject;
$eventdata->fullmessage = $this->notificationtext;
$eventdata->fullmessageformat = FORMAT_PLAIN;
$eventdata->fullmessagehtml = $this->notificationhtml;
$eventdata->notification = 1;
$eventdata->smallmessage = get_string('smallmessagedigest', 'forum', $this->sentcount);
return message_send($eventdata);
}
/**
* Helper to fetch the required renderer, instantiating as required.
*
* @param int $maildigest The type of mail digest being sent
* @param bool $html Whether to fetch the HTML renderer
* @return \core_renderer
*/
protected function get_renderer($maildigest, $html = false) {
global $PAGE;
$type = $maildigest == 2 ? 'emaildigestbasic' : 'emaildigestfull';
$target = $html ? 'htmlemail' : 'textemail';
if (!isset($this->renderers[$target][$type])) {
$this->renderers[$target][$type] = $PAGE->get_renderer('mod_forum', $type, $target);
}
return $this->renderers[$target][$type];
}
}
@@ -0,0 +1,582 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file defines an adhoc task to send notifications.
*
* @package mod_forum
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_forum\task;
defined('MOODLE_INTERNAL') || die();
/**
* Adhoc task to send user forum notifications.
*
* @package mod_forum
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class send_user_notifications extends \core\task\adhoc_task {
// Use the logging trait to get some nice, juicy, logging.
use \core\task\logging_trait;
/**
* @var \stdClass A shortcut to $USER.
*/
protected $recipient;
/**
* @var \stdClass[] List of courses the messages are in, indexed by courseid.
*/
protected $courses = [];
/**
* @var \stdClass[] List of forums the messages are in, indexed by courseid.
*/
protected $forums = [];
/**
* @var int[] List of IDs for forums in each course.
*/
protected $courseforums = [];
/**
* @var \stdClass[] List of discussions the messages are in, indexed by forumid.
*/
protected $discussions = [];
/**
* @var \stdClass[] List of IDs for discussions in each forum.
*/
protected $forumdiscussions = [];
/**
* @var \stdClass[] List of posts the messages are in, indexed by discussionid.
*/
protected $posts = [];
/**
* @var bool[] Whether the user can view fullnames for each forum.
*/
protected $viewfullnames = [];
/**
* @var bool[] Whether the user can post in each discussion.
*/
protected $canpostto = [];
/**
* @var \renderer[] The renderers.
*/
protected $renderers = [];
/**
* @var \core\message\inbound\address_manager The inbound message address manager.
*/
protected $inboundmanager;
/**
* @var array List of users.
*/
protected $users = [];
/**
* Send out messages.
* @throws \moodle_exception
*/
public function execute() {
global $CFG;
// Raise the time limit for each discussion.
\core_php_time_limit::raise(120);
$this->recipient = \core_user::get_user($this->get_userid());
// Create the generic messageinboundgenerator.
$this->inboundmanager = new \core\message\inbound\address_manager();
$this->inboundmanager->set_handler('\mod_forum\message\inbound\reply_handler');
$data = $this->get_custom_data();
$this->prepare_data((array) $data);
$failedposts = [];
$markposts = [];
$errorcount = 0;
$sentcount = 0;
$this->log_start("Sending messages to {$this->recipient->username} ({$this->recipient->id})");
foreach ($this->courses as $course) {
$coursecontext = \context_course::instance($course->id);
if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
// The course is hidden and the user does not have access to it.
// Permissions may have changed since it was queued.
continue;
}
foreach ($this->courseforums[$course->id] as $forumid) {
$forum = $this->forums[$forumid];
$cm = get_fast_modinfo($course)->instances['forum'][$forumid];
$modcontext = \context_module::instance($cm->id);
foreach (array_values($this->forumdiscussions[$forumid]) as $discussionid) {
$discussion = $this->discussions[$discussionid];
if (!forum_user_can_see_discussion($forum, $discussion, $modcontext, $this->recipient)) {
// User cannot see this discussion.
// Permissions may have changed since it was queued.
continue;
}
if (!\mod_forum\subscriptions::is_subscribed($this->recipient->id, $forum, $discussionid, $cm)) {
// The user does not subscribe to this forum as a whole, or to this specific discussion.
continue;
}
foreach ($this->posts[$discussionid] as $post) {
if (!forum_user_can_see_post($forum, $discussion, $post, $this->recipient, $cm)) {
// User cannot see this post.
// Permissions may have changed since it was queued.
continue;
}
if ($this->send_post($course, $forum, $discussion, $post, $cm, $modcontext)) {
$this->log("Post {$post->id} sent", 1);
// Mark post as read if forum_usermarksread is set off.
if (!$CFG->forum_usermarksread) {
$markposts[$post->id] = true;
}
$sentcount++;
} else {
$this->log("Failed to send post {$post->id}", 1);
$failedposts[] = $post->id;
$errorcount++;
}
}
}
}
}
$this->log_finish("Sent {$sentcount} messages with {$errorcount} failures");
if (!empty($markposts)) {
if (get_user_preferences('forum_markasreadonnotification', 1, $this->recipient->id) == 1) {
$this->log_start("Marking posts as read");
$count = count($markposts);
forum_tp_mark_posts_read($this->recipient, array_keys($markposts));
$this->log_finish("Marked {$count} posts as read");
}
}
if ($errorcount > 0 and $sentcount === 0) {
// All messages errored. So fail.
throw new \moodle_exception('Error sending posts.');
} else if ($errorcount > 0) {
// Requeue failed messages as a new task.
$task = new send_user_notifications();
$task->set_userid($this->recipient->id);
$task->set_custom_data($failedposts);
$task->set_component('mod_forum');
$task->set_next_run_time(time() + MINSECS);
$task->set_fail_delay(MINSECS);
\core\task\manager::reschedule_or_queue_adhoc_task($task);
}
}
/**
* Prepare all data for this run.
*
* Take all post ids, and fetch the relevant authors, discussions, forums, and courses for them.
*
* @param int[] $postids The list of post IDs
*/
protected function prepare_data(array $postids) {
global $DB;
if (empty($postids)) {
return;
}
list($in, $params) = $DB->get_in_or_equal(array_values($postids));
$sql = "SELECT p.*, f.id AS forum, f.course
FROM {forum_posts} p
INNER JOIN {forum_discussions} d ON d.id = p.discussion
INNER JOIN {forum} f ON f.id = d.forum
WHERE p.id {$in}";
$posts = $DB->get_recordset_sql($sql, $params);
$discussionids = [];
$forumids = [];
$courseids = [];
$userids = [];
foreach ($posts as $post) {
$discussionids[] = $post->discussion;
$forumids[] = $post->forum;
$courseids[] = $post->course;
$userids[] = $post->userid;
unset($post->forum);
if (!isset($this->posts[$post->discussion])) {
$this->posts[$post->discussion] = [];
}
$this->posts[$post->discussion][$post->id] = $post;
}
$posts->close();
if (empty($discussionids)) {
// All posts have been removed since the task was queued.
return;
}
// Fetch all discussions.
list($in, $params) = $DB->get_in_or_equal(array_values($discussionids));
$this->discussions = $DB->get_records_select('forum_discussions', "id {$in}", $params);
foreach ($this->discussions as $discussion) {
if (empty($this->forumdiscussions[$discussion->forum])) {
$this->forumdiscussions[$discussion->forum] = [];
}
$this->forumdiscussions[$discussion->forum][] = $discussion->id;
}
// Fetch all forums.
list($in, $params) = $DB->get_in_or_equal(array_values($forumids));
$this->forums = $DB->get_records_select('forum', "id {$in}", $params);
foreach ($this->forums as $forum) {
if (empty($this->courseforums[$forum->course])) {
$this->courseforums[$forum->course] = [];
}
$this->courseforums[$forum->course][] = $forum->id;
}
// Fetch all courses.
list($in, $params) = $DB->get_in_or_equal(array_values($courseids));
$this->courses = $DB->get_records_select('course', "id $in", $params);
// Fetch all authors.
list($in, $params) = $DB->get_in_or_equal(array_values($userids));
$users = $DB->get_recordset_select('user', "id $in", $params);
foreach ($users as $user) {
$this->minimise_user_record($user);
$this->users[$user->id] = $user;
}
$users->close();
// Fill subscription caches for each forum.
// These are per-user.
foreach (array_values($forumids) as $id) {
\mod_forum\subscriptions::fill_subscription_cache($id);
\mod_forum\subscriptions::fill_discussion_subscription_cache($id);
}
}
/**
* Send the specified post for the current user.
*
* @param \stdClass $course
* @param \stdClass $forum
* @param \stdClass $discussion
* @param \stdClass $post
* @param \stdClass $cm
* @param \context $context
*/
protected function send_post($course, $forum, $discussion, $post, $cm, $context) {
global $CFG, $PAGE;
$author = $this->get_post_author($post->userid, $course, $forum, $cm, $context);
if (empty($author)) {
return false;
}
// Prepare to actually send the post now, and build up the content.
$cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
$shortname = format_string($course->shortname, true, [
'context' => \context_course::instance($course->id),
]);
// Generate a reply-to address from using the Inbound Message handler.
$replyaddress = $this->get_reply_address($course, $forum, $discussion, $post, $cm, $context);
$data = new \mod_forum\output\forum_post_email(
$course,
$cm,
$forum,
$discussion,
$post,
$author,
$this->recipient,
$this->can_post($course, $forum, $discussion, $post, $cm, $context)
);
$data->viewfullnames = $this->can_view_fullnames($course, $forum, $discussion, $post, $cm, $context);
// Not all of these variables are used in the default string but are made available to support custom subjects.
$site = get_site();
$a = (object) [
'subject' => $data->get_subject(),
'forumname' => $cleanforumname,
'sitefullname' => format_string($site->fullname),
'siteshortname' => format_string($site->shortname),
'courseidnumber' => $data->get_courseidnumber(),
'coursefullname' => $data->get_coursefullname(),
'courseshortname' => $data->get_coursename(),
];
$postsubject = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
// Message headers are stored against the message author.
$author->customheaders = $this->get_message_headers($course, $forum, $discussion, $post, $a, $data);
$eventdata = new \core\message\message();
$eventdata->courseid = $course->id;
$eventdata->component = 'mod_forum';
$eventdata->name = 'posts';
$eventdata->userfrom = $author;
$eventdata->userto = $this->recipient;
$eventdata->subject = $postsubject;
$eventdata->fullmessage = $this->get_renderer()->render($data);
$eventdata->fullmessageformat = FORMAT_PLAIN;
$eventdata->fullmessagehtml = $this->get_renderer(true)->render($data);
$eventdata->notification = 1;
$eventdata->replyto = $replyaddress;
if (!empty($replyaddress)) {
// Add extra text to email messages if they can reply back.
$eventdata->set_additional_content('email', [
'fullmessage' => [
'footer' => "\n\n" . get_string('replytopostbyemail', 'mod_forum'),
],
'fullmessagehtml' => [
'footer' => \html_writer::tag('p', get_string('replytopostbyemail', 'mod_forum')),
]
]);
}
$eventdata->smallmessage = get_string('smallmessage', 'forum', (object) [
'user' => fullname($author),
'forumname' => "$shortname: " . format_string($forum->name, true) . ": " . $discussion->name,
'message' => $post->message,
]);
$contexturl = new \moodle_url('/mod/forum/discuss.php', ['d' => $discussion->id], "p{$post->id}");
$eventdata->contexturl = $contexturl->out();
$eventdata->contexturlname = $discussion->name;
// User image.
$userpicture = new \user_picture($author);
$userpicture->size = 1; // Use f1 size.
$userpicture->includetoken = $this->recipient->id; // Generate an out-of-session token for the user receiving the message.
$eventdata->customdata = [
'cmid' => $cm->id,
'instance' => $forum->id,
'discussionid' => $discussion->id,
'postid' => $post->id,
'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
'actionbuttons' => [
'reply' => get_string_manager()->get_string('reply', 'forum', null, $eventdata->userto->lang),
],
];
return message_send($eventdata);
}
/**
* Fetch and initialise the post author.
*
* @param int $userid The id of the user to fetch
* @param \stdClass $course
* @param \stdClass $forum
* @param \stdClass $cm
* @param \context $context
* @return \stdClass
*/
protected function get_post_author($userid, $course, $forum, $cm, $context) {
if (!isset($this->users[$userid])) {
// This user no longer exists.
return false;
}
$user = $this->users[$userid];
if (!isset($user->groups)) {
// Initialise the groups list.
$user->groups = [];
}
if (!isset($user->groups[$forum->id])) {
$user->groups[$forum->id] = groups_get_all_groups($course->id, $user->id, $cm->groupingid);
}
// Clone the user object to prevent leaks between messages.
return (object) (array) $user;
}
/**
* Helper to fetch the required renderer, instantiating as required.
*
* @param bool $html Whether to fetch the HTML renderer
* @return \core_renderer
*/
protected function get_renderer($html = false) {
global $PAGE;
$target = $html ? 'htmlemail' : 'textemail';
if (!isset($this->renderers[$target])) {
$this->renderers[$target] = $PAGE->get_renderer('mod_forum', 'email', $target);
}
return $this->renderers[$target];
}
/**
* Get the list of message headers.
*
* @param \stdClass $course
* @param \stdClass $forum
* @param \stdClass $discussion
* @param \stdClass $post
* @param \stdClass $a The list of strings for this post
* @param \core\message\message $message The message to be sent
* @return \stdClass
*/
protected function get_message_headers($course, $forum, $discussion, $post, $a, $message) {
$cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
$viewurl = new \moodle_url('/mod/forum/view.php', ['f' => $forum->id]);
$headers = [
// Headers to make emails easier to track.
'List-Id: "' . $cleanforumname . '" ' . generate_email_messageid('moodleforum' . $forum->id),
'List-Help: ' . $viewurl->out(),
'Message-ID: ' . forum_get_email_message_id($post->id, $this->recipient->id),
'X-Course-Id: ' . $course->id,
'X-Course-Name: '. format_string($course->fullname, true),
// Headers to help prevent auto-responders.
'Precedence: Bulk',
'X-Auto-Response-Suppress: All',
'Auto-Submitted: auto-generated',
'List-Unsubscribe: <' . $message->get_unsubscribediscussionlink() . '>',
];
$rootid = forum_get_email_message_id($discussion->firstpost, $this->recipient->id);
if ($post->parent) {
// This post is a reply, so add reply header (RFC 2822).
$parentid = forum_get_email_message_id($post->parent, $this->recipient->id);
$headers[] = "In-Reply-To: $parentid";
// If the post is deeply nested we also reference the parent message id and
// the root message id (if different) to aid threading when parts of the email
// conversation have been deleted (RFC1036).
if ($post->parent != $discussion->firstpost) {
$headers[] = "References: $rootid $parentid";
} else {
$headers[] = "References: $parentid";
}
} else {
// If the message IDs that Moodle creates are overwritten then referencing these
// IDs here will enable then to still thread correctly with the first email.
$headers[] = "In-Reply-To: $rootid";
$headers[] = "References: $rootid";
}
// MS Outlook / Office uses poorly documented and non standard headers, including
// Thread-Topic which overrides the Subject and shouldn't contain Re: or Fwd: etc.
$aclone = (object) (array) $a;
$aclone->subject = $discussion->name;
$threadtopic = html_to_text(get_string('postmailsubject', 'forum', $aclone), 0);
$headers[] = "Thread-Topic: $threadtopic";
$headers[] = "Thread-Index: " . substr($rootid, 1, 28);
return $headers;
}
/**
* Get a no-reply address for this user to reply to the current post.
*
* @param \stdClass $course
* @param \stdClass $forum
* @param \stdClass $discussion
* @param \stdClass $post
* @param \stdClass $cm
* @param \context $context
* @return string
*/
protected function get_reply_address($course, $forum, $discussion, $post, $cm, $context) {
if ($this->can_post($course, $forum, $discussion, $post, $cm, $context)) {
// Generate a reply-to address from using the Inbound Message handler.
$this->inboundmanager->set_data($post->id);
return $this->inboundmanager->generate($this->recipient->id);
}
// TODO Check if we can return a string.
// This will be controlled by the event.
return null;
}
/**
* Check whether the user can post.
*
* @param \stdClass $course
* @param \stdClass $forum
* @param \stdClass $discussion
* @param \stdClass $post
* @param \stdClass $cm
* @param \context $context
* @return bool
*/
protected function can_post($course, $forum, $discussion, $post, $cm, $context) {
if (!isset($this->canpostto[$discussion->id])) {
$this->canpostto[$discussion->id] = forum_user_can_post($forum, $discussion, $this->recipient, $cm, $course, $context);
}
return $this->canpostto[$discussion->id];
}
/**
* Check whether the user can view full names of other users.
*
* @param \stdClass $course
* @param \stdClass $forum
* @param \stdClass $discussion
* @param \stdClass $post
* @param \stdClass $cm
* @param \context $context
* @return bool
*/
protected function can_view_fullnames($course, $forum, $discussion, $post, $cm, $context) {
if (!isset($this->viewfullnames[$forum->id])) {
$this->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $context, $this->recipient->id);
}
return $this->viewfullnames[$forum->id];
}
/**
* Removes properties from user record that are not necessary for sending post notifications.
*
* @param \stdClass $user
*/
protected function minimise_user_record(\stdClass $user) {
// We store large amount of users in one huge array, make sure we do not store info there we do not actually
// need in mail generation code or messaging.
unset($user->institution);
unset($user->department);
unset($user->address);
unset($user->city);
unset($user->currentlogin);
unset($user->description);
unset($user->descriptionformat);
}
}