Merge branch 'MDL-64017_master' of git://github.com/markn86/moodle

This commit is contained in:
Adrian Greeve 2019-04-18 16:14:57 +08:00
commit 8c67db30a6
22 changed files with 969 additions and 26 deletions

View File

@ -114,6 +114,7 @@ class manager {
if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_SELF) {
return $savemessage->id;
}
$localisedeventdata->conversationtype = $conv->type;
// We treat individual conversations the same as any direct message with 'userfrom' and 'userto' specified.
// We know the other user, so set the 'userto' field so that the event code will get access to this field.
@ -206,10 +207,9 @@ class manager {
}
// Fill in the array of processors to be used based on default and user preferences.
// This applies only to individual conversations. Messages to group conversations ignore processors.
// Do not process muted conversations.
$processorlist = [];
if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL && !$recipient->ismuted) {
if (!$recipient->ismuted) {
foreach ($processors as $processor) {
// Skip adding processors for internal user, if processor doesn't support sending message to internal user.
if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {

View File

@ -77,6 +77,9 @@ class message {
/** @var int The conversation id where userfrom is sending this message. */
private $convid;
/** @var int The conversation type, eg. \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL */
private $conversationtype;
/** @var object|int The user who is receiving from which is sending this message. */
private $userto;
@ -133,6 +136,7 @@ class message {
'name',
'userfrom',
'convid',
'conversationtype',
'userto',
'subject',
'fullmessage',

View File

@ -889,13 +889,30 @@ class core_messagelib_testcase extends advanced_testcase {
$this->preventResetByRollback();
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course();
// Create some users and a conversation between them.
$user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
set_config('allowedemaildomains', 'example.com');
$conversation = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
[$user1->id, $user2->id, $user3->id], 'Group project discussion');
// Create a group in the course.
$group1 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
groups_add_member($group1->id, $user1->id);
groups_add_member($group1->id, $user2->id);
groups_add_member($group1->id, $user3->id);
$conversation = \core_message\api::create_conversation(
\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
[$user1->id, $user2->id, $user3->id],
'Group project discussion',
\core_message\api::MESSAGE_CONVERSATION_ENABLED,
'core_group',
'groups',
$group1->id,
context_course::instance($course->id)->id
);
// Generate the message.
$message = new \core\message\message();
@ -920,11 +937,14 @@ class core_messagelib_testcase extends advanced_testcase {
set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'email', $user2);
set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'email', $user3);
// Now, send a message and verify the email processor is NOT hit.
$sink = $this->redirectEmails();
// Now, send a message and verify the email processor are hit.
$messageid = message_send($message);
$sink = $this->redirectEmails();
$task = new \message_email\task\send_email_task();
$task->execute();
$emails = $sink->get_messages();
$this->assertCount(0, $emails);
$this->assertCount(2, $emails);
// Verify the record was created in 'messages'.
$recordexists = $DB->record_exists('messages', ['id' => $messageid]);
@ -955,14 +975,29 @@ class core_messagelib_testcase extends advanced_testcase {
$this->preventResetByRollback();
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course();
$user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
set_config('allowedemaildomains', 'example.com');
// Create a conversation.
$conversation = \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
[$user1->id, $user2->id, $user3->id], 'Group project discussion');
// Create a group in the course.
$group1 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
groups_add_member($group1->id, $user1->id);
groups_add_member($group1->id, $user2->id);
groups_add_member($group1->id, $user3->id);
$conversation = \core_message\api::create_conversation(
\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
[$user1->id, $user2->id, $user3->id],
'Group project discussion',
\core_message\api::MESSAGE_CONVERSATION_ENABLED,
'core_group',
'groups',
$group1->id,
context_course::instance($course->id)->id
);
// Test basic email redirection.
$this->assertFileExists("$CFG->dirroot/message/output/email/version.php");
@ -992,20 +1027,20 @@ class core_messagelib_testcase extends advanced_testcase {
$transaction = $DB->start_delegated_transaction();
$sink = $this->redirectEmails();
$messageid = message_send($message);
message_send($message);
$emails = $sink->get_messages();
$this->assertCount(0, $emails);
$savedmessage = $DB->get_record('messages', array('id' => $messageid), '*', MUST_EXIST);
$sink->clear();
$this->assertFalse($DB->record_exists('message_user_actions', array()));
$DB->delete_records('messages', array());
$events = $eventsink->get_events();
$this->assertCount(0, $events);
$eventsink->clear();
$transaction->allow_commit();
$events = $eventsink->get_events();
$task = new \message_email\task\send_email_task();
$task->execute();
$emails = $sink->get_messages();
$this->assertCount(0, $emails); // Email processor is disabled for messages to group conversations.
$this->assertCount(2, $emails);
$this->assertCount(1, $events);
$this->assertInstanceOf('\core\event\group_message_sent', $events[0]);
}

View File

@ -1 +1 @@
define(["jquery","core/custom_interaction_events","core/pubsub","core_message/message_drawer_view_contact","core_message/message_drawer_view_contacts","core_message/message_drawer_view_conversation","core_message/message_drawer_view_group_info","core_message/message_drawer_view_overview","core_message/message_drawer_view_search","core_message/message_drawer_view_settings","core_message/message_drawer_router","core_message/message_drawer_routes","core_message/message_drawer_events"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){var n={PANEL_BODY_CONTAINER:'[data-region="panel-body-container"]',PANEL_HEADER_CONTAINER:'[data-region="panel-header-container"]',VIEW_CONTACT:'[data-region="view-contact"]',VIEW_CONTACTS:'[data-region="view-contacts"]',VIEW_CONVERSATION:'[data-region="view-conversation"]',VIEW_GROUP_INFO:'[data-region="view-group-info"]',VIEW_OVERVIEW:'[data-region="view-overview"]',VIEW_SEARCH:'[data-region="view-search"]',VIEW_SETTINGS:'[data-region="view-settings"]',ROUTES:"[data-route]",ROUTES_BACK:"[data-route-back]",HEADER_CONTAINER:'[data-region="header-container"]',BODY_CONTAINER:'[data-region="body-container"]',FOOTER_CONTAINER:'[data-region="footer-container"]'},o=function(a,b,c){var d=b.find(n.HEADER_CONTAINER).find(c);d.length||(d=b.find(n.PANEL_HEADER_CONTAINER).find(c));var e=b.find(n.BODY_CONTAINER).find(c);e.length||(e=b.find(n.PANEL_BODY_CONTAINER).find(c));var f=b.find(n.FOOTER_CONTAINER).find(c);return[a,d.length?d:null,e.length?e:null,f.length?f:null]},p=[[l.VIEW_CONTACT,n.VIEW_CONTACT,d.show,d.description],[l.VIEW_CONTACTS,n.VIEW_CONTACTS,e.show,e.description],[l.VIEW_CONVERSATION,n.VIEW_CONVERSATION,f.show,f.description],[l.VIEW_GROUP_INFO,n.VIEW_GROUP_INFO,g.show,g.description],[l.VIEW_OVERVIEW,n.VIEW_OVERVIEW,h.show,h.description],[l.VIEW_SEARCH,n.VIEW_SEARCH,i.show,i.description],[l.VIEW_SETTINGS,n.VIEW_SETTINGS,j.show,j.description]],q=function(a,b){p.forEach(function(c){k.add(a,c[0],o(a,b,c[1]),c[2],c[3])})},r=function(a,b){b.attr("data-shown")||(k.go(a,l.VIEW_OVERVIEW),b.attr("data-shown",!0)),b.removeClass("hidden"),b.attr("aria-expanded",!0),b.attr("aria-hidden",!1)},s=function(a){a.addClass("hidden"),a.attr("aria-expanded",!1),a.attr("aria-hidden",!0)},t=function(a){return!a.hasClass("hidden")},u=function(d,e,f){b.define(e,[b.events.activate]);var g=/^data-route-param-?(\d*)$/;e.on(b.events.activate,n.ROUTES,function(b,c){for(var e=a(b.target).closest(n.ROUTES),f=e.attr("data-route"),h=[],i=0;i<e[0].attributes.length;i++)h.push(e[0].attributes[i]);var j=h.filter(function(a){var b=a.nodeName,c=g.test(b);return c});j.sort(function(a,b){var c=g.exec(a.nodeName),d=g.exec(b.nodeName),e=c.length>1?c[1]:0,f=d.length>1?d[1]:0;return e<f?-1:f<e?1:0});var l=j.map(function(a){return a.nodeValue}),m=[d,f].concat(l);k.go.apply(null,m),c.originalEvent.preventDefault()}),e.on(b.events.activate,n.ROUTES_BACK,function(a,b){k.back(d),b.originalEvent.preventDefault()}),f||(c.subscribe(m.SHOW,function(){r(d,e)}),c.subscribe(m.HIDE,function(){s(e)}),c.subscribe(m.TOGGLE_VISIBILITY,function(){t(e)?s(e):r(d,e)})),c.subscribe(m.SHOW_CONVERSATION,function(a){r(d,e),k.go(d,l.VIEW_CONVERSATION,a)}),c.subscribe(m.CREATE_CONVERSATION_WITH_USER,function(a){r(d,e),k.go(d,l.VIEW_CONVERSATION,null,"create",a)}),c.subscribe(m.SHOW_SETTINGS,function(){r(d,e),k.go(d,l.VIEW_SETTINGS)}),c.subscribe(m.PREFERENCES_UPDATED,function(a){var b=a.filter(function(a){return"message_entertosend"==a.type}),c=b.length?b[0]:null;if(c){var d=e.find(n.FOOTER_CONTAINER).find(n.VIEW_CONVERSATION);d.attr("data-enter-to-send",c.value)}})},v=function(b,c,d,e,f){b=a(b),q(c,b),u(c,b,d),d&&(r(c,b),e&&(f?k.go(c,l.VIEW_CONVERSATION,f):k.go(c,l.VIEW_CONVERSATION,null,"create",e)))};return{init:v}});
define(["jquery","core/custom_interaction_events","core/pubsub","core_message/message_drawer_view_contact","core_message/message_drawer_view_contacts","core_message/message_drawer_view_conversation","core_message/message_drawer_view_group_info","core_message/message_drawer_view_overview","core_message/message_drawer_view_search","core_message/message_drawer_view_settings","core_message/message_drawer_router","core_message/message_drawer_routes","core_message/message_drawer_events"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){var n={PANEL_BODY_CONTAINER:'[data-region="panel-body-container"]',PANEL_HEADER_CONTAINER:'[data-region="panel-header-container"]',VIEW_CONTACT:'[data-region="view-contact"]',VIEW_CONTACTS:'[data-region="view-contacts"]',VIEW_CONVERSATION:'[data-region="view-conversation"]',VIEW_GROUP_INFO:'[data-region="view-group-info"]',VIEW_OVERVIEW:'[data-region="view-overview"]',VIEW_SEARCH:'[data-region="view-search"]',VIEW_SETTINGS:'[data-region="view-settings"]',ROUTES:"[data-route]",ROUTES_BACK:"[data-route-back]",HEADER_CONTAINER:'[data-region="header-container"]',BODY_CONTAINER:'[data-region="body-container"]',FOOTER_CONTAINER:'[data-region="footer-container"]'},o=function(a,b,c){var d=b.find(n.HEADER_CONTAINER).find(c);d.length||(d=b.find(n.PANEL_HEADER_CONTAINER).find(c));var e=b.find(n.BODY_CONTAINER).find(c);e.length||(e=b.find(n.PANEL_BODY_CONTAINER).find(c));var f=b.find(n.FOOTER_CONTAINER).find(c);return[a,d.length?d:null,e.length?e:null,f.length?f:null]},p=[[l.VIEW_CONTACT,n.VIEW_CONTACT,d.show,d.description],[l.VIEW_CONTACTS,n.VIEW_CONTACTS,e.show,e.description],[l.VIEW_CONVERSATION,n.VIEW_CONVERSATION,f.show,f.description],[l.VIEW_GROUP_INFO,n.VIEW_GROUP_INFO,g.show,g.description],[l.VIEW_OVERVIEW,n.VIEW_OVERVIEW,h.show,h.description],[l.VIEW_SEARCH,n.VIEW_SEARCH,i.show,i.description],[l.VIEW_SETTINGS,n.VIEW_SETTINGS,j.show,j.description]],q=function(a,b){p.forEach(function(c){k.add(a,c[0],o(a,b,c[1]),c[2],c[3])})},r=function(a,b){b.attr("data-shown")||(k.go(a,l.VIEW_OVERVIEW),b.attr("data-shown",!0)),b.removeClass("hidden"),b.attr("aria-expanded",!0),b.attr("aria-hidden",!1)},s=function(a){a.addClass("hidden"),a.attr("aria-expanded",!1),a.attr("aria-hidden",!0)},t=function(a){return!a.hasClass("hidden")},u=function(d,e,f){b.define(e,[b.events.activate]);var g=/^data-route-param-?(\d*)$/;e.on(b.events.activate,n.ROUTES,function(b,c){for(var e=a(b.target).closest(n.ROUTES),f=e.attr("data-route"),h=[],i=0;i<e[0].attributes.length;i++)h.push(e[0].attributes[i]);var j=h.filter(function(a){var b=a.nodeName,c=g.test(b);return c});j.sort(function(a,b){var c=g.exec(a.nodeName),d=g.exec(b.nodeName),e=c.length>1?c[1]:0,f=d.length>1?d[1]:0;return e<f?-1:f<e?1:0});var l=j.map(function(a){return a.nodeValue}),m=[d,f].concat(l);k.go.apply(null,m),c.originalEvent.preventDefault()}),e.on(b.events.activate,n.ROUTES_BACK,function(a,b){k.back(d),b.originalEvent.preventDefault()}),f||(c.subscribe(m.SHOW,function(){r(d,e)}),c.subscribe(m.HIDE,function(){s(e)}),c.subscribe(m.TOGGLE_VISIBILITY,function(){t(e)?s(e):r(d,e)})),c.subscribe(m.SHOW_CONVERSATION,function(a){r(d,e),k.go(d,l.VIEW_CONVERSATION,a)}),c.subscribe(m.CREATE_CONVERSATION_WITH_USER,function(a){r(d,e),k.go(d,l.VIEW_CONVERSATION,null,"create",a)}),c.subscribe(m.SHOW_SETTINGS,function(){r(d,e),k.go(d,l.VIEW_SETTINGS)}),c.subscribe(m.PREFERENCES_UPDATED,function(a){var b=a.filter(function(a){return"message_entertosend"==a.type}),c=b.length?b[0]:null;if(c){var d=e.find(n.FOOTER_CONTAINER).find(n.VIEW_CONVERSATION);d.attr("data-enter-to-send",c.value)}})},v=function(b,c,d,e,f){b=a(b),q(c,b),u(c,b,d),d&&(r(c,b),e?f?k.go(c,l.VIEW_CONVERSATION,f):k.go(c,l.VIEW_CONVERSATION,null,"create",e):f&&k.go(c,l.VIEW_CONVERSATION,f))};return{init:v}});

View File

@ -276,12 +276,16 @@ function(
registerEventListeners(uniqueId, root, alwaysVisible);
if (alwaysVisible) {
show(uniqueId, root);
// Are we sending to a specific user?
if (sendToUser) {
// Check if a conversation already exists, if not, create one.
if (conversationId) {
Router.go(uniqueId, Routes.VIEW_CONVERSATION, conversationId);
} else {
Router.go(uniqueId, Routes.VIEW_CONVERSATION, null, 'create', sendToUser);
}
} else if (conversationId) { // We aren't sending to a specific user, but to a group conversation.
Router.go(uniqueId, Routes.VIEW_CONVERSATION, conversationId);
}
}
};

View File

@ -764,6 +764,9 @@ class helper {
if ($sendtouser) {
$templatecontext['sendtouser'] = $sendtouser;
}
if ($conversationid) {
$templatecontext['conversationid'] = $conversationid;
}

View File

@ -40,10 +40,20 @@ $id = optional_param('id', 0, PARAM_INT);
// We no longer support viewing another user's messaging area (that can be achieved
// via the 'Log-in as' feature). The 'user2' value takes preference over 'id'.
$userid = optional_param('user2', $id, PARAM_INT);
$conversationid = optional_param('convid', null, PARAM_INT);
if (!core_user::is_real_user($userid)) {
$userid = null;
}
// You can specify either a user, or a conversation, not both.
if ($userid) {
$conversationid = \core_message\api::get_conversation_between_users([$USER->id, $userid]);
} else if ($conversationid) {
// Check that the user belongs to the conversation.
if (!\core_message\api::is_user_in_conversation($USER->id, $conversationid)) {
$conversationid = null;
}
}
if ($userid) {
$recipient = new stdClass();
@ -73,12 +83,6 @@ $usernode->remove();
$settings = $PAGE->settingsnav->find('messages', null);
$settings->make_active();
// Check if there is an existing conversation with the supplied user (if there is one).
$conversationid = null;
if ($userid) {
$conversationid = \core_message\api::get_conversation_between_users([$USER->id, $userid]);
}
echo $OUTPUT->header();
// Display a message if the messages have not been migrated yet.
if (!get_user_preferences('core_message_migrate_data', false)) {

View File

@ -0,0 +1,46 @@
<?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/>.
/**
* Email digest as html renderer.
*
* @package message_email
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace message_email\output\email;
defined('MOODLE_INTERNAL') || die();
/**
* Email digest as html renderer.
*
* @package message_email
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class renderer extends \message_email\output\renderer {
/**
* The template name for this renderer.
*
* @return string
*/
public function get_template_name() {
return 'email_digest_html';
}
}

View File

@ -0,0 +1,46 @@
<?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/>.
/**
* Email digest as text renderer.
*
* @package message_email
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace message_email\output\email;
defined('MOODLE_INTERNAL') || die();
/**
* Email digest as text renderer.
*
* @package message_email
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class renderer_textemail extends \message_email\output\renderer {
/**
* The template name for this renderer.
*
* @return string
*/
public function get_template_name() {
return 'email_digest_text';
}
}

View File

@ -0,0 +1,136 @@
<?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/>.
/**
* Email digest renderable.
*
* @package message_email
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace message_email\output;
defined('MOODLE_INTERNAL') || die();
/**
* Email digest renderable.
*
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class email_digest implements \renderable, \templatable {
/**
* @var array The conversations
*/
protected $conversations = array();
/**
* @var array The messages
*/
protected $messages = array();
/**
* @var \stdClass The user we want to send the digest email to
*/
protected $userto;
/**
* The email_digest constructor.
*
* @param \stdClass $userto
*/
public function __construct(\stdClass $userto) {
$this->userto = $userto;
}
/**
* Adds another conversation to this digest.
*
* @param \stdClass $conversation The conversation from the 'message_conversations' table.
*/
public function add_conversation(\stdClass $conversation) {
$this->conversations[$conversation->id] = $conversation;
}
/**
* Adds another message to this digest, using the conversation id it belongs to as a key.
*
* @param \stdClass $message The message from the 'messages' table.
*/
public function add_message(\stdClass $message) {
$this->messages[$message->conversationid][] = $message;
}
/**
* Export this data so it can be used as the context for a mustache template.
*
* @param \renderer_base $renderer The render to be used for formatting the email
* @return \stdClass The data ready for use in a mustache template
*/
public function export_for_template(\renderer_base $renderer) {
// Prepare the data we are going to send to the template.
$data = new \stdClass();
$data->conversations = [];
// Don't do anything if there are no messages.
foreach ($this->conversations as $conversation) {
$messages = $this->messages[$conversation->id] ?? [];
if (empty($messages)) {
continue;
}
$viewallmessageslink = new \moodle_url('/message/index.php', ['convid' => $conversation->id]);
$conversationformatted = new \stdClass();
$conversationformatted->groupname = $conversation->name;
$conversationformatted->coursename = $conversation->coursename;
$conversationformatted->numberofunreadmessages = count($messages);
$conversationformatted->messages = [];
$conversationformatted->viewallmessageslink = \html_writer::link($viewallmessageslink,
get_string('emaildigestviewallmessages', 'message_email'));
// We only display the last 3 messages.
$messages = array_slice($messages, -3, 3, true);
foreach ($messages as $message) {
$user = new \stdClass();
username_load_fields_from_object($user, $message);
$user->id = $message->useridfrom;
$messageformatted = new \stdClass();
$messageformatted->userfullname = fullname($user);
$messageformatted->message = message_format_message_text($message);
// Check if the message was sent today.
$istoday = userdate($message->timecreated, 'Y-m-d') == userdate(time(), 'Y-m-d');
if ($istoday) {
$timesent = userdate($message->timecreated, get_string('strftimetime24', 'langconfig'));
} else {
$timesent = userdate($message->timecreated, get_string('strftimedatefullshort', 'langconfig'));
}
$messageformatted->timesent = $timesent;
$conversationformatted->messages[] = $messageformatted;
}
$data->conversations[] = $conversationformatted;
}
return $data;
}
}

View File

@ -0,0 +1,50 @@
<?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/>.
/**
* Contains renderer class.
*
* @package message_email
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace message_email\output;
defined('MOODLE_INTERNAL') || die();
use plugin_renderer_base;
/**
* Renderer class.
*
* @package message_email
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class renderer extends plugin_renderer_base {
/**
* Formats the email used to send the certificate by the email_certificate_task.
*
* @param email_digest $emaildigest The certificate to email
* @return string
*/
public function render_email_digest(email_digest $emaildigest) {
$data = $emaildigest->export_for_template($this);
return $this->render_from_template('message_email/' . $this->get_template_name(), $data);
}
}

View File

@ -51,6 +51,15 @@ class provider implements
* @return collection A listing of user data stored through this system.
*/
public static function get_metadata(collection $collection) : collection {
$messageemailmessages = [
'useridto' => 'privacy:metadata:message_email_messages:useridto',
'conversationid' => 'privacy:metadata:message_email_messages:conversationid',
'messageid' => 'privacy:metadata:message_email_messages:messageid',
];
// Note - this data gets deleted once the scheduled task runs.
$collection->add_database_table('message_email_messages',
$messageemailmessages, 'privacy:metadata:message_email_messages');
$collection->link_external_location('smtp', [
'recipient' => 'privacy:metadata:recipient',
'userfrom' => 'privacy:metadata:userfrom',

View File

@ -0,0 +1,173 @@
<?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/>.
/**
* Contains the class responsible for sending emails as a digest.
*
* @package message_email
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace message_email\task;
use core\task\scheduled_task;
use moodle_recordset;
defined('MOODLE_INTERNAL') || die();
/**
* Class responsible for sending emails as a digest.
*
* @package message_email
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class send_email_task extends scheduled_task {
/**
* @var int $maxid This is the maximum id of the message in 'message_email_messages'.
* We use this so we know what records to process, as more records may be added
* while this task runs.
*/
private $maxid;
/**
* Get a descriptive name for this task (shown to admins).
*
* @return string
*/
public function get_name() {
return get_string('tasksendemail', 'message_email');
}
/**
* Send out emails.
*/
public function execute() {
global $DB, $PAGE;
// Get the maximum id we are going to use.
// We use this as records may be added to the table while this task runs.
$this->maxid = $DB->get_field_sql("SELECT MAX(id) FROM {message_email_messages}");
// We are going to send these emails from 'noreplyaddress'.
$noreplyuser = \core_user::get_noreply_user();
// The renderers used for sending emails.
$htmlrenderer = $PAGE->get_renderer('message_email', 'email', 'htmlemail');
$textrenderer = $PAGE->get_renderer('message_email', 'email', 'textemail');
// Keep track of which emails failed to send.
$users = $this->get_unique_users();
foreach ($users as $user) {
$hascontent = false;
$renderable = new \message_email\output\email_digest($user);
$conversations = $this->get_conversations_for_user($user->id);
foreach ($conversations as $conversation) {
$renderable->add_conversation($conversation);
$messages = $this->get_users_messages_for_conversation($conversation->id, $user->id);
if ($messages->valid()) {
$hascontent = true;
foreach ($messages as $message) {
$renderable->add_message($message);
}
}
$messages->close();
}
$conversations->close();
if ($hascontent) {
$subject = get_string('emaildigestsubject', 'message_email');
$message = $textrenderer->render($renderable);
$messagehtml = $htmlrenderer->render($renderable);
if (email_to_user($user, $noreplyuser, $subject, $message, $messagehtml)) {
$DB->delete_records_select('message_email_messages', 'useridto = ? AND id <= ?', [$user->id, $this->maxid]);
}
}
}
$users->close();
}
/**
* Returns an array of users in the given conversation.
*
* @return moodle_recordset A moodle_recordset instance.
*/
private function get_unique_users() : moodle_recordset {
global $DB;
$subsql = 'SELECT DISTINCT(useridto) as id
FROM {message_email_messages}
WHERE id <= ?';
$sql = "SELECT *
FROM {user} u
WHERE id IN ($subsql)";
return $DB->get_recordset_sql($sql, [$this->maxid]);
}
/**
* Returns an array of unique conversations that require processing.
*
* @param int $userid The ID of the user we are sending a digest to.
* @return moodle_recordset A moodle_recordset instance.
*/
private function get_conversations_for_user(int $userid) : moodle_recordset {
global $DB;
// We shouldn't be joining directly on the group table as group
// conversations may (in the future) be something created that
// isn't related to an actual group in a course. However, for
// now this will have to do before 3.7 code freeze.
// See related MDL-63814.
$sql = "SELECT mc.id, mc.name, c.id as courseid, c.fullname as coursename, g.id as groupid, g.picture, g.hidepicture
FROM {message_conversations} mc
JOIN {groups} g
ON mc.itemid = g.id
JOIN {course} c
ON g.courseid = c.id
JOIN {message_email_messages} mem
ON mem.conversationid = mc.id
WHERE mem.useridto = ?
AND mem.id <= ?";
return $DB->get_recordset_sql($sql, [$userid, $this->maxid]);
}
/**
* Returns the messages to send to a user for a given conversation
*
* @param int $conversationid
* @param int $userid
* @return moodle_recordset A moodle_recordset instance.
*/
protected function get_users_messages_for_conversation(int $conversationid, int $userid) : moodle_recordset {
global $DB;
$usernamefields = \user_picture::fields('u');
$sql = "SELECT $usernamefields, m.*
FROM {messages} m
JOIN {user} u
ON u.id = m.useridfrom
JOIN {message_email_messages} mem
ON mem.messageid = m.id
WHERE mem.useridto = ?
AND mem.conversationid = ?
AND mem.id <= ?";
return $DB->get_recordset_sql($sql, [$userid, $conversationid, $this->maxid]);
}
}

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8" ?>
<XMLDB PATH="message/output/email/db" VERSION="20190325" COMMENT="XMLDB file for Moodle message/output/email"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../lib/xmldb/xmldb.xsd"
>
<TABLES>
<TABLE NAME="message_email_messages" COMMENT="Keeps track of what emails to send in an email digest">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="useridto" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="conversationid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="messageid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id"/>
<KEY NAME="useridto" TYPE="foreign" FIELDS="useridto" REFTABLE="user" REFFIELDS="id"/>
<KEY NAME="conversationid" TYPE="foreign" FIELDS="conversationid" REFTABLE="message_conversations" REFFIELDS="id"/>
<KEY NAME="messageid" TYPE="foreign" FIELDS="messageid" REFTABLE="messages" REFFIELDS="id"/>
</KEYS>
</TABLE>
</TABLES>
</XMLDB>

View File

@ -0,0 +1,38 @@
<?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 tasks performed by the plugin.
*
* @package message_email
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
// List of tasks.
$tasks = array(
array(
'classname' => 'message_email\task\send_email_task',
'blocking' => 0,
'minute' => 0,
'hour' => 22,
'day' => '*',
'dayofweek' => '*',
'month' => '*'
)
);

View File

@ -30,7 +30,9 @@ defined('MOODLE_INTERNAL') || die();
* @param int $oldversion The version that we are upgrading from
*/
function xmldb_message_email_upgrade($oldversion) {
global $CFG;
global $DB;
$dbman = $DB->get_manager();
// Automatically generated Moodle v3.3.0 release upgrade line.
// Put any upgrade step following this.
@ -44,5 +46,30 @@ function xmldb_message_email_upgrade($oldversion) {
// Automatically generated Moodle v3.6.0 release upgrade line.
// Put any upgrade step following this.
if ($oldversion < 2019032500) {
// Define table message_email_messages to be created.
$table = new xmldb_table('message_email_messages');
// Adding fields to table message_email_messages.
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('useridto', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
$table->add_field('conversationid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
$table->add_field('messageid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
// Adding keys to table message_email_messages.
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$table->add_key('useridto', XMLDB_KEY_FOREIGN, array('useridto'), 'user', array('id'));
$table->add_key('conversationid', XMLDB_KEY_FOREIGN, array('conversationid'), 'message_conversations', array('id'));
$table->add_key('messageid', XMLDB_KEY_FOREIGN, array('messageid'), 'messages', array('id'));
// Conditionally launch create table for message_email_messages.
if (!$dbman->table_exists($table)) {
$dbman->create_table($table);
}
// Savepoint reached.
upgrade_plugin_savepoint(true, 2019032500, 'message', 'email');
}
return true;
}

View File

@ -23,6 +23,9 @@
*/
$string['email'] = 'Send email notifications to';
$string['emaildigestsubject'] = 'Message digest';
$string['emaildigestunreadmessages'] = 'Unread messages';
$string['emaildigestviewallmessages'] = 'View all messages';
$string['emailonlyfromnoreplyaddress'] = 'Always send email from the no-reply address?';
$string['ifemailleftempty'] = 'Leave empty to send notifications to {$a}';
$string['pluginname'] = 'Email';
@ -31,8 +34,14 @@ $string['privacy:metadata:attachname'] = 'The name of the attached file (extensi
$string['privacy:metadata:externalpurpose'] = 'This information is sent to an external SMTP server to be ultimately delivered as an email to the recipient.';
$string['privacy:metadata:fullmessage'] = 'The full message in a given format.';
$string['privacy:metadata:fullmessagehtml'] = 'The full version of the message.';
$string['privacy:metadata:message_email_messages'] = 'The list of users enrolled via an LTI provider';
$string['privacy:metadata:message_email_messages:conversationid'] = 'The id of the conversation being sent to';
$string['privacy:metadata:message_email_messages:messageid'] = 'The id of the message being sent';
$string['privacy:metadata:message_email_messages:useridto'] = 'The user receiving the message.';
$string['privacy:metadata:recipient'] = 'The recipient of the message.';
$string['privacy:metadata:replyto'] = 'The email address to reply to.';
$string['privacy:metadata:replytoname'] = 'Name of reply to recipient.';
$string['privacy:metadata:subject'] = 'The subject line of the message.';
$string['privacy:metadata:userfrom'] = 'The user sending the message.';
$string['tasksendemail'] = 'Task responsible for sending messages as a digest.';

View File

@ -37,7 +37,7 @@ class message_output_email extends message_output {
* @param object $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid
*/
function send_message($eventdata) {
global $CFG;
global $CFG, $DB;
// skip any messaging suspended and deleted users
if ($eventdata->userto->auth === 'nologin' or $eventdata->userto->suspended or $eventdata->userto->deleted) {
@ -90,8 +90,25 @@ class message_output_email extends message_output {
}
}
$result = email_to_user($recipient, $eventdata->userfrom, $eventdata->subject, $eventdata->fullmessage,
$eventdata->fullmessagehtml, $attachment, $attachname, true, $replyto, $replytoname);
// We email messages from private conversations straight away, but for group we add them to a table to be sent later.
$emailuser = true;
if (!$eventdata->notification) {
if ($eventdata->conversationtype == \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP) {
$emailuser = false;
}
}
if ($emailuser) {
$result = email_to_user($recipient, $eventdata->userfrom, $eventdata->subject, $eventdata->fullmessage,
$eventdata->fullmessagehtml, $attachment, $attachname, true, $replyto, $replytoname);
} else {
$messagetosend = new stdClass();
$messagetosend->useridfrom = $eventdata->userfrom->id;
$messagetosend->useridto = $recipient->id;
$messagetosend->conversationid = $eventdata->convid;
$messagetosend->messageid = $eventdata->savedmessageid;
$result = $DB->insert_record('message_email_messages', $messagetosend, false);
}
// Remove an attachment file if any.
if (!empty($attachment) && file_exists($attachment)) {

View File

@ -0,0 +1,123 @@
{{!
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/>.
}}
{{!
@template email_message/email_digest_html
Template which defines a forum post for sending in a single-post HTML email.
Classes required for JS:
* none
Data attributes required for JS:
* none
Example context (json):
{
"conversations": [
{
"groupname": "Blue Students",
"coursename": "Math 101",
"numberofunreadmessages": "2",
"messages": [
{
"userfullname": "Chris Cross",
"message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla neque nunc, bibendum ac vestibulum sit amet, scelerisque luctus sem. Maecenas ultricies hendrerit augue, ac venenatis odio volutpat nec",
"timesent": "10:12"
},
{
"userfullname": "Irene Ipsum",
"message": "Etiam a tristique risus. Pellentesque id tellus eget elit dictum varius id sed sapien",
"timesent": "10:14"
}
],
"viewallmessageslink": "http://example.com"
}
]
}
}}
<head>
<style>
.table {
color: #373a3c;
border: 1px solid #dee2e6;
border-collapse: collapse;
font-size: 15px;
margin-bottom: 20px;
}
.table th {
text-align: left;
font-weight: normal;
background-color: #F2F2F2;
border-bottom: 1px solid #dee2e6;
padding: 10px;
}
.table td {
padding: 10px;
vertical-align: top;
}
.badge {
background-color: #1177d1;
color: #ffffff;
padding: 2px;
border-radius: 50%;
width: 15px;
height: 15px;
display: inline-block;
text-align: center;
}
.nowrap {
white-space: nowrap;
}
.text-right {
text-align: right;
}
</style>
</head>
{{#conversations}}
<table class="table">
<thead>
<tr>
<th>
<strong>{{ groupname }}</strong><br>
{{ coursename }}
</th>
<th class="nowrap">
<span class="badge">{{ numberofunreadmessages }}</span> {{#str}} emaildigestunreadmessages, message_email {{/str}}
</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>
<strong>{{{ userfullname }}}</strong>
<p>{{{ message }}}</p>
</td>
<td class="text-right">
{{ timesent }}
</td>
</tr>
{{/messages}}
<tr>
<td colspan="2">
{{{viewallmessageslink}}}
</td>
</tr>
</tbody>
</table>
{{/conversations}}

View File

@ -0,0 +1,69 @@
{{!
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/>.
}}
{{!
@template email_message/email_digest_text
Template which defines a forum post for sending in a single-post HTML email.
Classes required for JS:
* none
Data attributes required for JS:
* none
Example context (json):
{
"conversations": [
{
"groupname": "Blue Students",
"coursename": "Math 101",
"numberofunreadmessages": "2",
"messages": [
{
"userfullname": "Chris Cross",
"message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla neque nunc, bibendum ac vestibulum sit amet, scelerisque luctus sem. Maecenas ultricies hendrerit augue, ac venenatis odio volutpat nec",
"timesent": "10:12"
},
{
"userfullname": "Irene Ipsum",
"message": "Etiam a tristique risus. Pellentesque id tellus eget elit dictum varius id sed sapien",
"timesent": "10:14"
}
],
"viewallmessageslink": "http://example.com"
}
]
}
}}
{{#conversations}}
{{groupname}}
{{coursename}}
{{numberofunreadmessages}} {{#str}}emaildigestunreadmessages, message_email{{/str}}
{{#messages}}
{{userfullname}}
{{message}}
{{timesent}}
{{viewallmessageslink}}
{{/messages}}
{{/conversations}}

View File

@ -0,0 +1,128 @@
<?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/>.
/**
* Tests the send email task.
*
* @package message_email
* @category test
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/message/tests/messagelib_test.php');
/**
* Class for testing the send email task.
*
* @package message_email
* @category test
* @copyright 2019 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class core_message_send_email_task_testcase extends advanced_testcase {
/**
* Test sending email task.
*/
public function test_sending_email_task() {
global $DB;
$this->preventResetByRollback(); // Messaging is not compatible with transactions.
$this->resetAfterTest();
// Create a course.
$course = $this->getDataGenerator()->create_course();
$user1 = $this->getDataGenerator()->create_and_enrol($course, 'student');
$user2 = $this->getDataGenerator()->create_and_enrol($course, 'student');
// Create two groups in the course.
$group1 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
$group2 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
groups_add_member($group1->id, $user1->id);
groups_add_member($group2->id, $user1->id);
groups_add_member($group1->id, $user2->id);
groups_add_member($group2->id, $user2->id);
$conversation1 = \core_message\api::create_conversation(
\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
[$user1->id, $user2->id],
'Group 1', \core_message\api::MESSAGE_CONVERSATION_ENABLED,
'core_group',
'groups',
$group1->id,
context_course::instance($course->id)->id
);
$conversation2 = \core_message\api::create_conversation(
\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
[$user1->id, $user2->id],
'Group 2',
\core_message\api::MESSAGE_CONVERSATION_ENABLED,
'core_group',
'groups',
$group2->id,
context_course::instance($course->id)->id
);
// Go through each conversation.
if ($conversations = $DB->get_records('message_conversations')) {
foreach ($conversations as $conversation) {
$conversationid = $conversation->id;
$message = new \core\message\message();
$message->courseid = 1;
$message->component = 'moodle';
$message->name = 'instantmessage';
$message->userfrom = $user1;
$message->convid = $conversationid;
$message->subject = 'message subject';
$message->fullmessage = 'message body';
$message->fullmessageformat = FORMAT_MARKDOWN;
$message->fullmessagehtml = '<p>message body</p>';
$message->smallmessage = 'small message';
$message->notification = '0';
message_send($message);
}
}
$this->assertEquals(2, $DB->count_records('message_email_messages'));
// Only 1 email is sent as the 2 messages are included in it at a digest.
$sink = $this->redirectEmails();
$task = new \message_email\task\send_email_task();
$task->execute();
$this->assertEquals(1, $sink->count());
// Confirm table was emptied after task was run.
$this->assertEquals(0, $DB->count_records('message_email_messages'));
// Confirm running it again does not send another.
$sink = $this->redirectEmails();
$task = new \message_email\task\send_email_task();
$task->execute();
$this->assertEquals(0, $sink->count());
}
}

View File

@ -24,6 +24,6 @@
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2018120300; // The current plugin version (Date: YYYYMMDDXX)
$plugin->version = 2019032500; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2018112800; // Requires this Moodle version
$plugin->component = 'message_email'; // Full name of the plugin (used for diagnostics)