2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Contains class used to return information to display for the message area.
20 * @package core_message
21 * @copyright 2016 Mark Nelson <markn@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 namespace core_message;
27 use core_favourites\local\entity\favourite;
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->dirroot . '/lib/messagelib.php');
34 * Class used to return information to display for the message area.
36 * @copyright 2016 Mark Nelson <markn@moodle.com>
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 * The action for reading a message.
44 const MESSAGE_ACTION_READ = 1;
47 * The action for deleting a message.
49 const MESSAGE_ACTION_DELETED = 2;
52 * The privacy setting for being messaged by anyone within courses user is member of.
54 const MESSAGE_PRIVACY_COURSEMEMBER = 0;
57 * The privacy setting for being messaged only by contacts.
59 const MESSAGE_PRIVACY_ONLYCONTACTS = 1;
62 * The privacy setting for being messaged by anyone on the site.
64 const MESSAGE_PRIVACY_SITE = 2;
67 * An individual conversation.
69 const MESSAGE_CONVERSATION_TYPE_INDIVIDUAL = 1;
72 * A group conversation.
74 const MESSAGE_CONVERSATION_TYPE_GROUP = 2;
77 * The state for an enabled conversation area.
79 const MESSAGE_CONVERSATION_ENABLED = 1;
82 * The state for a disabled conversation area.
84 const MESSAGE_CONVERSATION_DISABLED = 0;
87 * Handles searching for messages in the message area.
89 * @param int $userid The user id doing the searching
90 * @param string $search The string the user is searching
91 * @param int $limitfrom
92 * @param int $limitnum
95 public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
98 // Get the user fields we want.
99 $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
100 $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
102 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto, m.subject, m.fullmessage, m.fullmessagehtml, m.fullmessageformat,
103 m.smallmessage, m.timecreated, 0 as isread, $ufields, mub.id as userfrom_blocked, $ufields2,
104 mub2.id as userto_blocked
107 ON u.id = m.useridfrom
108 INNER JOIN {message_conversations} mc
109 ON mc.id = m.conversationid
110 INNER JOIN {message_conversation_members} mcm
111 ON mcm.conversationid = m.conversationid
113 ON u2.id = mcm.userid
114 LEFT JOIN {message_users_blocked} mub
115 ON (mub.blockeduserid = u.id AND mub.userid = ?)
116 LEFT JOIN {message_users_blocked} mub2
117 ON (mub2.blockeduserid = u2.id AND mub2.userid = ?)
118 LEFT JOIN {message_user_actions} mua
119 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
120 WHERE (m.useridfrom = ? OR mcm.userid = ?)
121 AND m.useridfrom != mcm.userid
125 AND " . $DB->sql_like('smallmessage', '?', false) . "
126 ORDER BY timecreated DESC";
128 $params = array($userid, $userid, $userid, self::MESSAGE_ACTION_DELETED, $userid, $userid, '%' . $search . '%');
130 // Convert the messages into searchable contacts with their last message being the message that was searched.
131 $conversations = array();
132 if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
133 foreach ($messages as $message) {
134 $prefix = 'userfrom_';
135 if ($userid == $message->useridfrom) {
137 // If it from the user, then mark it as read, even if it wasn't by the receiver.
138 $message->isread = true;
140 $blockedcol = $prefix . 'blocked';
141 $message->blocked = $message->$blockedcol ? 1 : 0;
143 $message->messageid = $message->id;
144 $conversations[] = helper::create_contact($message, $prefix);
148 return $conversations;
152 * Handles searching for user in a particular course in the message area.
154 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
155 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
156 * But we are deprecating data_for_messagearea_search_users_in_course external function.
157 * Followup: MDL-63915
159 * @param int $userid The user id doing the searching
160 * @param int $courseid The id of the course we are searching in
161 * @param string $search The string the user is searching
162 * @param int $limitfrom
163 * @param int $limitnum
166 public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
169 // Get all the users in the course.
170 list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
171 $sql = "SELECT u.*, mub.id as isblocked
175 LEFT JOIN {message_users_blocked} mub
176 ON (mub.blockeduserid = u.id AND mub.userid = :userid)
177 WHERE u.deleted = 0";
178 // Add more conditions.
179 $fullname = $DB->sql_fullname();
180 $sql .= " AND u.id != :userid2
181 AND " . $DB->sql_like($fullname, ':search', false) . "
182 ORDER BY " . $DB->sql_fullname();
183 $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
185 // Convert all the user records into contacts.
187 if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
188 foreach ($users as $user) {
189 $user->blocked = $user->isblocked ? 1 : 0;
190 $contacts[] = helper::create_contact($user);
198 * Handles searching for user in the message area.
200 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
201 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
202 * But we are deprecating data_for_messagearea_search_users external function.
203 * Followup: MDL-63915
205 * @param int $userid The user id doing the searching
206 * @param string $search The string the user is searching
207 * @param int $limitnum
210 public static function search_users($userid, $search, $limitnum = 0) {
213 // Used to search for contacts.
214 $fullname = $DB->sql_fullname();
215 $ufields = \user_picture::fields('u', array('lastaccess'));
217 // Users not to include.
218 $excludeusers = array($userid, $CFG->siteguest);
219 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
221 $params = array('search' => '%' . $search . '%', 'userid1' => $userid, 'userid2' => $userid, 'userid3' => $userid);
223 // Ok, let's search for contacts first.
225 $sql = "SELECT $ufields, mub.id as isuserblocked
227 JOIN {message_contacts} mc
228 ON (u.id = mc.contactid AND mc.userid = :userid1) OR (u.id = mc.userid AND mc.contactid = :userid2)
229 LEFT JOIN {message_users_blocked} mub
230 ON (mub.userid = :userid3 AND mub.blockeduserid = u.id)
233 AND " . $DB->sql_like($fullname, ':search', false) . "
235 ORDER BY " . $DB->sql_fullname();
237 if ($users = $DB->get_records_sql($sql, $params + $excludeparams, 0, $limitnum)) {
238 foreach ($users as $user) {
239 $user->blocked = $user->isuserblocked ? 1 : 0;
240 $contacts[] = helper::create_contact($user);
244 // Now, let's get the courses.
245 // Make sure to limit searches to enrolled courses.
246 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
248 // Really we want the user to be able to view the participants if they have the capability
249 // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
250 // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
251 // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
252 if ($arrcourses = \core_course_category::search_courses(array('search' => $search), array('limit' => $limitnum),
253 array('moodle/course:viewparticipants'))) {
254 foreach ($arrcourses as $course) {
255 if (isset($enrolledcourses[$course->id])) {
256 $data = new \stdClass();
257 $data->id = $course->id;
258 $data->shortname = $course->shortname;
259 $data->fullname = $course->fullname;
265 // Let's get those non-contacts.
266 $noncontacts = array();
267 if ($CFG->messagingallusers) {
268 // In case $CFG->messagingallusers is enabled, search for all users site-wide but are not user's contact.
269 $sql = "SELECT $ufields
271 LEFT JOIN {message_users_blocked} mub
272 ON (mub.userid = :userid1 AND mub.blockeduserid = u.id)
275 AND " . $DB->sql_like($fullname, ':search', false) . "
277 AND NOT EXISTS (SELECT mc.id
278 FROM {message_contacts} mc
279 WHERE (mc.userid = u.id AND mc.contactid = :userid2)
280 OR (mc.userid = :userid3 AND mc.contactid = u.id))
281 ORDER BY " . $DB->sql_fullname();
283 // In case $CFG->messagingallusers is disabled, search for users you have a conversation with.
284 // Messaging setting could change, so could exist an old conversation with users you cannot message anymore.
285 $sql = "SELECT $ufields, mub.id as isuserblocked
287 LEFT JOIN {message_users_blocked} mub
288 ON (mub.userid = :userid1 AND mub.blockeduserid = u.id)
289 INNER JOIN {message_conversation_members} cm
291 INNER JOIN {message_conversation_members} cm2
292 ON cm.conversationid = cm2.conversationid AND cm2.userid = :userid
295 AND " . $DB->sql_like($fullname, ':search', false) . "
297 AND NOT EXISTS (SELECT mc.id
298 FROM {message_contacts} mc
299 WHERE (mc.userid = u.id AND mc.contactid = :userid2)
300 OR (mc.userid = :userid3 AND mc.contactid = u.id))
301 ORDER BY " . $DB->sql_fullname();
302 $params['userid'] = $userid;
304 if ($users = $DB->get_records_sql($sql, $params + $excludeparams, 0, $limitnum)) {
305 foreach ($users as $user) {
306 $noncontacts[] = helper::create_contact($user);
310 return array($contacts, $courses, $noncontacts);
314 * Handles searching for user.
316 * @param int $userid The user id doing the searching
317 * @param string $search The string the user is searching
318 * @param int $limitfrom
319 * @param int $limitnum
322 public static function message_search_users(int $userid, string $search, int $limitfrom = 0, int $limitnum = 1000) : array {
325 // Used to search for contacts.
326 $fullname = $DB->sql_fullname();
328 // Users not to include.
329 $excludeusers = array($userid, $CFG->siteguest);
330 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
332 $params = array('search' => '%' . $search . '%', 'userid1' => $userid, 'userid2' => $userid);
334 // Ok, let's search for contacts first.
337 JOIN {message_contacts} mc
338 ON (u.id = mc.contactid AND mc.userid = :userid1) OR (u.id = mc.userid AND mc.contactid = :userid2)
341 AND " . $DB->sql_like($fullname, ':search', false) . "
343 ORDER BY " . $DB->sql_fullname();
344 $foundusers = $DB->get_records_sql_menu($sql, $params + $excludeparams, $limitfrom, $limitnum);
346 $orderedcontacs = array();
347 if (!empty($foundusers)) {
348 $contacts = helper::get_member_info($userid, array_keys($foundusers));
349 // The get_member_info returns an associative array, so is not ordered in the same way.
350 // We need to reorder it again based on query's result.
351 foreach ($foundusers as $key => $value) {
352 $contact = $contacts[$key];
353 $contact->conversations = self::get_conversations_between_users($userid, $key, 0, 1000);
354 $orderedcontacs[] = $contact;
358 // Let's get those non-contacts.
359 if ($CFG->messagingallusers) {
360 // In case $CFG->messagingallusers is enabled, search for all users site-wide but are not user's contact.
365 AND " . $DB->sql_like($fullname, ':search', false) . "
367 AND NOT EXISTS (SELECT mc.id
368 FROM {message_contacts} mc
369 WHERE (mc.userid = u.id AND mc.contactid = :userid1)
370 OR (mc.userid = :userid2 AND mc.contactid = u.id))
371 ORDER BY " . $DB->sql_fullname();
373 // In case $CFG->messagingallusers is disabled, search for users you have a conversation with.
374 // Messaging setting could change, so could exist an old conversation with users you cannot message anymore.
377 INNER JOIN {message_conversation_members} cm
379 INNER JOIN {message_conversation_members} cm2
380 ON cm.conversationid = cm2.conversationid AND cm2.userid = :userid
383 AND " . $DB->sql_like($fullname, ':search', false) . "
385 AND NOT EXISTS (SELECT mc.id
386 FROM {message_contacts} mc
387 WHERE (mc.userid = u.id AND mc.contactid = :userid1)
388 OR (mc.userid = :userid2 AND mc.contactid = u.id))
389 ORDER BY " . $DB->sql_fullname();
390 $params['userid'] = $userid;
392 $foundusers = $DB->get_records_sql_menu($sql, $params + $excludeparams, $limitfrom, $limitnum);
394 $orderednoncontacs = array();
395 if (!empty($foundusers)) {
396 $noncontacts = helper::get_member_info($userid, array_keys($foundusers));
397 // The get_member_info returns an associative array, so is not ordered in the same way.
398 // We need to reorder it again based on query's result.
399 foreach ($foundusers as $key => $value) {
400 $contact = $noncontacts[$key];
401 $contact->conversations = self::get_conversations_between_users($userid, $key, 0, 1000);
402 $orderednoncontacs[] = $contact;
406 return array($orderedcontacs, $orderednoncontacs);
410 * Gets extra fields, like image url and subname for any conversations linked to components.
412 * The subname is like a subtitle for the conversation, to compliment it's name.
413 * The imageurl is the location of the image for the conversation, as might be seen on a listing of conversations for a user.
415 * @param array $conversations a list of conversations records.
416 * @return array the array of subnames, index by conversation id.
417 * @throws \coding_exception
418 * @throws \dml_exception
420 protected static function get_linked_conversation_extra_fields(array $conversations) : array {
423 $linkedconversations = [];
424 foreach ($conversations as $conversation) {
425 if (!is_null($conversation->component) && !is_null($conversation->itemtype)) {
426 $linkedconversations[$conversation->component][$conversation->itemtype][$conversation->id]
427 = $conversation->itemid;
430 if (empty($linkedconversations)) {
434 // TODO: MDL-63814: Working out the subname for linked conversations should be done in a generic way.
435 // Get the itemid, but only for course group linked conversation for now.
437 if (!empty($linkeditems = $linkedconversations['core_group']['groups'])) { // Format: [conversationid => itemid].
438 // Get the name of the course to which the group belongs.
439 list ($groupidsql, $groupidparams) = $DB->get_in_or_equal(array_values($linkeditems), SQL_PARAMS_NAMED, 'groupid');
440 $sql = "SELECT g.*, c.shortname as courseshortname
444 WHERE g.id $groupidsql";
445 $courseinfo = $DB->get_records_sql($sql, $groupidparams);
446 foreach ($linkeditems as $convid => $groupid) {
447 if (array_key_exists($groupid, $courseinfo)) {
448 $group = $courseinfo[$groupid];
450 $extrafields[$convid]['subname'] = format_string($courseinfo[$groupid]->courseshortname);
453 $extrafields[$convid]['imageurl'] = '';
454 if ($url = get_group_picture_url($group, $group->courseid, true)) {
455 $extrafields[$convid]['imageurl'] = $url->out(false);
465 * Returns the contacts and their conversation to display in the contacts area.
468 * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
469 * to retrieve too much information in a single call will cause performance problems.
472 * This function has specifically been altered to break each of the data sets it
473 * requires into separate database calls. This is to avoid the performance problems
474 * observed when attempting to join large data sets (e.g. the message tables and
477 * While it is possible to gather the data in a single query, and it may even be
478 * more efficient with a correctly tuned database, we have opted to trade off some of
479 * the benefits of a single query in order to ensure this function will work on
480 * most databases with default tunings and with large data sets.
482 * @param int $userid The user id
483 * @param int $limitfrom
484 * @param int $limitnum
485 * @param int $type the type of the conversation, if you wish to filter to a certain type (see api constants).
486 * @param bool $favourites whether to include NO favourites (false) or ONLY favourites (true), or null to ignore this setting.
487 * @return array the array of conversations
488 * @throws \moodle_exception
490 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20, int $type = null,
491 bool $favourites = null) {
494 if (!is_null($type) && !in_array($type, [self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
495 self::MESSAGE_CONVERSATION_TYPE_GROUP])) {
496 throw new \moodle_exception("Invalid value ($type) for type param, please see api constants.");
499 // We need to know which conversations are favourites, so we can either:
500 // 1) Include the 'isfavourite' attribute on conversations (when $favourite = null and we're including all conversations)
501 // 2) Restrict the results to ONLY those conversations which are favourites (when $favourite = true)
502 // 3) Restrict the results to ONLY those conversations which are NOT favourites (when $favourite = false).
503 $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
504 $favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
505 $favouriteconversationids = array_column($favouriteconversations, 'itemid');
506 if ($favourites && empty($favouriteconversationids)) {
507 return []; // If we are aiming to return ONLY favourites, and we have none, there's nothing more to do.
510 // CONVERSATIONS AND MOST RECENT MESSAGE.
511 // Include those conversations with messages first (ordered by most recent message, desc), then add any conversations which
512 // don't have messages, such as newly created group conversations.
513 // Because we're sorting by message 'timecreated', those conversations without messages could be at either the start or the
514 // end of the results (behaviour for sorting of nulls differs between DB vendors), so we use the case to presort these.
516 // If we need to return ONLY favourites, or NO favourites, generate the SQL snippet.
518 $favouriteparams = [];
519 if (null !== $favourites && !empty($favouriteconversationids)) {
520 list ($insql, $favouriteparams) =
521 $DB->get_in_or_equal($favouriteconversationids, SQL_PARAMS_NAMED, 'favouriteids', $favourites);
522 $favouritesql = " AND mc.id {$insql} ";
525 // If we need to restrict type, generate the SQL snippet.
526 $typesql = !is_null($type) ? " AND mc.type = :convtype " : "";
528 $sql = "SELECT m.id as messageid, mc.id as id, mc.name as conversationname, mc.type as conversationtype, m.useridfrom,
529 m.smallmessage, m.fullmessage, m.fullmessageformat, m.fullmessagehtml, m.timecreated, mc.component,
530 mc.itemtype, mc.itemid
531 FROM {message_conversations} mc
532 INNER JOIN {message_conversation_members} mcm
533 ON (mcm.conversationid = mc.id AND mcm.userid = :userid3)
535 SELECT m.conversationid, MAX(m.id) AS messageid
538 SELECT m.conversationid, MAX(m.timecreated) as maxtime
540 INNER JOIN {message_conversation_members} mcm
541 ON mcm.conversationid = m.conversationid
542 LEFT JOIN {message_user_actions} mua
543 ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
545 AND mcm.userid = :userid2
546 GROUP BY m.conversationid
548 ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
549 GROUP BY m.conversationid
551 ON lastmessage.conversationid = mc.id
552 LEFT JOIN {messages} m
553 ON m.id = lastmessage.messageid
554 WHERE mc.id IS NOT NULL $typesql $favouritesql
555 ORDER BY (CASE WHEN m.timecreated IS NULL THEN 0 ELSE 1 END) DESC, m.timecreated DESC, id DESC";
557 $params = array_merge($favouriteparams, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
558 'userid2' => $userid, 'userid3' => $userid, 'convtype' => $type]);
559 $conversationset = $DB->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
563 $individualmembers = [];
565 foreach ($conversationset as $conversation) {
566 $conversations[$conversation->id] = $conversation;
567 $members[$conversation->id] = [];
569 $conversationset->close();
571 // If there are no conversations found, then return early.
572 if (empty($conversations)) {
576 // COMPONENT-LINKED CONVERSATION FIELDS.
577 // Conversations linked to components may have extra information, such as:
578 // - subname: Essentially a subtitle for the conversation. So you'd have "name: subname".
579 // - imageurl: A URL to the image for the linked conversation.
580 // For now, this is ONLY course groups.
581 $convextrafields = self::get_linked_conversation_extra_fields($conversations);
584 // Ideally, we want to get 1 member for each conversation, but this depends on the type and whether there is a recent
587 // For 'individual' type conversations between 2 users, regardless of who sent the last message,
588 // we want the details of the other member in the conversation (i.e. not the current user).
590 // For 'group' type conversations, we want the details of the member who sent the last message, if there is one.
591 // This can be the current user or another group member, but for groups without messages, this will be empty.
593 // This also means that if type filtering is specified and only group conversations are returned, we don't need this extra
594 // query to get the 'other' user as we already have that information.
596 // Work out which members we have already, and which ones we might need to fetch.
597 // If all the last messages were from another user, then we don't need to fetch anything further.
598 foreach ($conversations as $conversation) {
599 if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
600 if (!is_null($conversation->useridfrom) && $conversation->useridfrom != $userid) {
601 $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
602 $individualmembers[$conversation->useridfrom] = $conversation->useridfrom;
604 $individualconversations[] = $conversation->id;
606 } else if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
607 // If we have a recent message, the sender is our member.
608 if (!is_null($conversation->useridfrom)) {
609 $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
610 $groupmembers[$conversation->useridfrom] = $conversation->useridfrom;
614 // If we need to fetch any member information for any of the individual conversations.
615 // This is the case if any of the individual conversations have a recent message sent by the current user.
616 if (!empty($individualconversations)) {
617 list ($icidinsql, $icidinparams) = $DB->get_in_or_equal($individualconversations, SQL_PARAMS_NAMED, 'convid');
618 $indmembersql = "SELECT mcm.id, mcm.conversationid, mcm.userid
619 FROM {message_conversation_members} mcm
620 WHERE mcm.conversationid $icidinsql
621 AND mcm.userid != :userid
623 $indmemberparams = array_merge($icidinparams, ['userid' => $userid]);
624 $conversationmembers = $DB->get_records_sql($indmembersql, $indmemberparams);
626 foreach ($conversationmembers as $mid => $member) {
627 $members[$member->conversationid][$member->userid] = $member->userid;
628 $individualmembers[$member->userid] = $member->userid;
632 // We could fail early here if we're sure that:
633 // a) we have no otherusers for all the conversations (users may have been deleted)
634 // b) we're sure that all conversations are individual (1:1).
636 // We need to pull out the list of users info corresponding to the memberids in the conversations.This
637 // needs to be done in a separate query to avoid doing a join on the messages tables and the user
638 // tables because on large sites these tables are massive which results in extremely slow
639 // performance (typically due to join buffer exhaustion).
640 if (!empty($individualmembers) || !empty($groupmembers)) {
641 // Now, we want to remove any duplicates from the group members array. For individual members we will
642 // be doing a more extensive call as we want their contact requests as well as privacy information,
643 // which is not necessary for group conversations.
644 $diffgroupmembers = array_diff($groupmembers, $individualmembers);
646 $individualmemberinfo = helper::get_member_info($userid, $individualmembers, true, true);
647 $groupmemberinfo = helper::get_member_info($userid, $diffgroupmembers);
649 // Don't use array_merge, as we lose array keys.
650 $memberinfo = $individualmemberinfo + $groupmemberinfo;
652 // Update the members array with the member information.
653 $deletedmembers = [];
654 foreach ($members as $convid => $memberarr) {
655 foreach ($memberarr as $key => $memberid) {
656 if (array_key_exists($memberid, $memberinfo)) {
657 // If the user is deleted, remember that.
658 if ($memberinfo[$memberid]->isdeleted) {
659 $deletedmembers[$convid][] = $memberid;
662 $members[$convid][$key] = clone $memberinfo[$memberid];
664 if ($conversations[$convid]->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
665 // Remove data we don't need for group.
666 $members[$convid][$key]->requirescontact = null;
667 $members[$convid][$key]->canmessage = null;
668 $members[$convid][$key]->contactrequests = [];
676 $cids = array_column($conversations, 'id');
677 list ($cidinsql, $cidinparams) = $DB->get_in_or_equal($cids, SQL_PARAMS_NAMED, 'convid');
678 $membercountsql = "SELECT conversationid, count(id) AS membercount
679 FROM {message_conversation_members} mcm
680 WHERE mcm.conversationid $cidinsql
681 GROUP BY mcm.conversationid";
682 $membercounts = $DB->get_records_sql($membercountsql, $cidinparams);
684 // UNREAD MESSAGE COUNT.
685 // Finally, let's get the unread messages count for this user so that we can add it
686 // to the conversation. Remember we need to ignore the messages the user sent.
687 $unreadcountssql = 'SELECT m.conversationid, count(m.id) as unreadcount
689 INNER JOIN {message_conversations} mc
690 ON mc.id = m.conversationid
691 INNER JOIN {message_conversation_members} mcm
692 ON m.conversationid = mcm.conversationid
693 LEFT JOIN {message_user_actions} mua
694 ON (mua.messageid = m.id AND mua.userid = ? AND
695 (mua.action = ? OR mua.action = ?))
697 AND m.useridfrom != ?
699 GROUP BY m.conversationid';
700 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
703 // Now, create the final return structure.
704 $arrconversations = [];
705 foreach ($conversations as $conversation) {
706 // Do not include any individual conversation which:
707 // a) Contains a deleted member or
708 // b) Does not contain a recent message for the user (this happens if the user has deleted all messages).
709 // Group conversations with deleted users or no messages are always returned.
710 if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL
711 && (isset($deletedmembers[$conversation->id]) || empty($conversation->messageid))) {
715 $conv = new \stdClass();
716 $conv->id = $conversation->id;
717 $conv->name = $conversation->conversationname;
718 $conv->subname = $convextrafields[$conv->id]['subname'] ?? null;
719 $conv->imageurl = $convextrafields[$conv->id]['imageurl'] ?? null;
720 $conv->type = $conversation->conversationtype;
721 $conv->membercount = $membercounts[$conv->id]->membercount;
722 $conv->isfavourite = in_array($conv->id, $favouriteconversationids);
723 $conv->isread = isset($unreadcounts[$conv->id]) ? false : true;
724 $conv->unreadcount = isset($unreadcounts[$conv->id]) ? $unreadcounts[$conv->id]->unreadcount : null;
725 $conv->members = $members[$conv->id];
727 // Add the most recent message information.
728 $conv->messages = [];
729 if ($conversation->smallmessage) {
730 $msg = new \stdClass();
731 $msg->id = $conversation->messageid;
732 $msg->text = message_format_message_text($conversation);
733 $msg->useridfrom = $conversation->useridfrom;
734 $msg->timecreated = $conversation->timecreated;
735 $conv->messages[] = $msg;
738 $arrconversations[] = $conv;
740 return $arrconversations;
744 * Returns all conversations between two users
746 * @param int $userid1 One of the user's id
747 * @param int $userid2 The other user's id
748 * @param int $limitfrom
749 * @param int $limitnum
751 * @throws \dml_exception
753 public static function get_conversations_between_users(int $userid1, int $userid2,
754 int $limitfrom = 0, int $limitnum = 20) : array {
758 if ($userid1 == $userid2) {
762 // Get all conversation where both user1 and user2 are members.
763 // TODO: Add subname value. Waiting for definite table structure.
764 $sql = "SELECT mc.id, mc.type, mc.name, mc.timecreated
765 FROM {message_conversations} mc
766 INNER JOIN {message_conversation_members} mcm1
767 ON mc.id = mcm1.conversationid
768 INNER JOIN {message_conversation_members} mcm2
769 ON mc.id = mcm2.conversationid
770 WHERE mcm1.userid = :userid1
771 AND mcm2.userid = :userid2
773 ORDER BY mc.timecreated DESC";
775 return $DB->get_records_sql($sql, array('userid1' => $userid1, 'userid2' => $userid2), $limitfrom, $limitnum);
779 * Mark a conversation as a favourite for the given user.
781 * @param int $conversationid the id of the conversation to mark as a favourite.
782 * @param int $userid the id of the user to whom the favourite belongs.
783 * @return favourite the favourite object.
784 * @throws \moodle_exception if the user or conversation don't exist.
786 public static function set_favourite_conversation(int $conversationid, int $userid) : favourite {
787 if (!self::is_user_in_conversation($userid, $conversationid)) {
788 throw new \moodle_exception("Conversation doesn't exist or user is not a member");
790 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
791 return $ufservice->create_favourite('core_message', 'message_conversations', $conversationid, \context_system::instance());
795 * Unset a conversation as a favourite for the given user.
797 * @param int $conversationid the id of the conversation to unset as a favourite.
798 * @param int $userid the id to whom the favourite belongs.
799 * @throws \moodle_exception if the favourite does not exist for the user.
801 public static function unset_favourite_conversation(int $conversationid, int $userid) {
802 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
803 $ufservice->delete_favourite('core_message', 'message_conversations', $conversationid, \context_system::instance());
807 * Returns the contacts to display in the contacts area.
809 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
810 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
811 * Followup: MDL-63915
813 * @param int $userid The user id
814 * @param int $limitfrom
815 * @param int $limitnum
818 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
823 FROM {message_contacts} mc
824 WHERE mc.userid = ? OR mc.contactid = ?
825 ORDER BY timecreated DESC";
826 if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
827 foreach ($contacts as $contact) {
828 if ($userid == $contact->userid) {
829 $contactids[] = $contact->contactid;
831 $contactids[] = $contact->userid;
836 if (!empty($contactids)) {
837 list($insql, $inparams) = $DB->get_in_or_equal($contactids);
839 $sql = "SELECT u.*, mub.id as isblocked
841 LEFT JOIN {message_users_blocked} mub
842 ON u.id = mub.blockeduserid
844 if ($contacts = $DB->get_records_sql($sql, $inparams)) {
846 foreach ($contacts as $contact) {
847 $contact->blocked = $contact->isblocked ? 1 : 0;
848 $arrcontacts[] = helper::create_contact($contact);
859 * Returns the an array of the users the given user is in a conversation
860 * with who are a contact and the number of unread messages.
862 * @param int $userid The user id
863 * @param int $limitfrom
864 * @param int $limitnum
867 public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
870 $userfields = \user_picture::fields('u', array('lastaccess'));
871 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
872 FROM {message_contacts} mc
874 ON (u.id = mc.contactid OR u.id = mc.userid)
875 LEFT JOIN {messages} m
876 ON ((m.useridfrom = mc.contactid OR m.useridfrom = mc.userid) AND m.useridfrom != ?)
877 LEFT JOIN {message_conversation_members} mcm
878 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
879 LEFT JOIN {message_user_actions} mua
880 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
881 LEFT JOIN {message_users_blocked} mub
882 ON (mub.userid = ? AND mub.blockeduserid = u.id)
885 AND (mc.userid = ? OR mc.contactid = ?)
888 GROUP BY $userfields";
890 return $DB->get_records_sql($unreadcountssql, [$userid, $userid, $userid, self::MESSAGE_ACTION_READ,
891 $userid, $userid, $userid, $userid], $limitfrom, $limitnum);
895 * Returns the an array of the users the given user is in a conversation
896 * with who are not a contact and the number of unread messages.
898 * @param int $userid The user id
899 * @param int $limitfrom
900 * @param int $limitnum
903 public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
906 $userfields = \user_picture::fields('u', array('lastaccess'));
907 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
909 INNER JOIN {messages} m
910 ON m.useridfrom = u.id
911 INNER JOIN {message_conversation_members} mcm
912 ON mcm.conversationid = m.conversationid
913 LEFT JOIN {message_user_actions} mua
914 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
915 LEFT JOIN {message_contacts} mc
916 ON (mc.userid = ? AND mc.contactid = u.id)
917 LEFT JOIN {message_users_blocked} mub
918 ON (mub.userid = ? AND mub.blockeduserid = u.id)
920 AND mcm.userid != m.useridfrom
925 GROUP BY $userfields";
927 return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
928 $limitfrom, $limitnum);
932 * Returns the messages to display in the message area.
934 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
935 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
936 * Followup: MDL-63915
938 * @param int $userid the current user
939 * @param int $otheruserid the other user
940 * @param int $limitfrom
941 * @param int $limitnum
942 * @param string $sort
943 * @param int $timefrom the time from the message being sent
944 * @param int $timeto the time up until the message being sent
947 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
948 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
950 if (!empty($timefrom)) {
951 // Get the conversation between userid and otheruserid.
952 $userids = [$userid, $otheruserid];
953 if (!$conversationid = self::get_conversation_between_users($userids)) {
954 // This method was always used for individual conversations.
955 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
956 $conversationid = $conversation->id;
959 // Check the cache to see if we even need to do a DB query.
960 $cache = \cache::make('core', 'message_time_last_message_between_users');
961 $key = helper::get_last_message_time_created_cache_key($conversationid);
962 $lastcreated = $cache->get($key);
964 // The last known message time is earlier than the one being requested so we can
965 // just return an empty result set rather than having to query the DB.
966 if ($lastcreated && $lastcreated < $timefrom) {
971 $arrmessages = array();
972 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
973 $sort, $timefrom, $timeto)) {
974 $arrmessages = helper::create_messages($userid, $messages);
981 * Returns the messages for the defined conversation.
983 * @param int $userid The current user.
984 * @param int $convid The conversation where the messages belong. Could be an object or just the id.
985 * @param int $limitfrom Return a subset of records, starting at this point (optional).
986 * @param int $limitnum Return a subset comprising this many records in total (optional, required if $limitfrom is set).
987 * @param string $sort The column name to order by including optionally direction.
988 * @param int $timefrom The time from the message being sent.
989 * @param int $timeto The time up until the message being sent.
990 * @return array of messages
992 public static function get_conversation_messages(int $userid, int $convid, int $limitfrom = 0, int $limitnum = 0,
993 string $sort = 'timecreated ASC', int $timefrom = 0, int $timeto = 0) : array {
995 if (!empty($timefrom)) {
996 // Check the cache to see if we even need to do a DB query.
997 $cache = \cache::make('core', 'message_time_last_message_between_users');
998 $key = helper::get_last_message_time_created_cache_key($convid);
999 $lastcreated = $cache->get($key);
1001 // The last known message time is earlier than the one being requested so we can
1002 // just return an empty result set rather than having to query the DB.
1003 if ($lastcreated && $lastcreated < $timefrom) {
1008 $arrmessages = array();
1009 if ($messages = helper::get_conversation_messages($userid, $convid, 0, $limitfrom, $limitnum, $sort, $timefrom, $timeto)) {
1010 $arrmessages = helper::format_conversation_messages($userid, $convid, $messages);
1013 return $arrmessages;
1017 * Returns the most recent message between two users.
1019 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1020 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1021 * Followup: MDL-63915
1023 * @param int $userid the current user
1024 * @param int $otheruserid the other user
1025 * @return \stdClass|null
1027 public static function get_most_recent_message($userid, $otheruserid) {
1028 // We want two messages here so we get an accurate 'blocktime' value.
1029 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
1030 // Swap the order so we now have them in historical order.
1031 $messages = array_reverse($messages);
1032 $arrmessages = helper::create_messages($userid, $messages);
1033 return array_pop($arrmessages);
1040 * Returns the most recent message in a conversation.
1042 * @param int $convid The conversation identifier.
1043 * @param int $currentuserid The current user identifier.
1044 * @return \stdClass|null The most recent message.
1046 public static function get_most_recent_conversation_message(int $convid, int $currentuserid = 0) {
1049 if (empty($currentuserid)) {
1050 $currentuserid = $USER->id;
1053 if ($messages = helper::get_conversation_messages($currentuserid, $convid, 0, 0, 1, 'timecreated DESC')) {
1054 $convmessages = helper::format_conversation_messages($currentuserid, $convid, $messages);
1055 return array_pop($convmessages['messages']);
1062 * Returns the profile information for a contact for a user.
1064 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1065 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1066 * Followup: MDL-63915
1068 * @param int $userid The user id
1069 * @param int $otheruserid The id of the user whose profile we want to view.
1072 public static function get_profile($userid, $otheruserid) {
1075 require_once($CFG->dirroot . '/user/lib.php');
1077 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
1079 // Create the data we are going to pass to the renderable.
1080 $data = new \stdClass();
1081 $data->userid = $otheruserid;
1082 $data->fullname = fullname($user);
1084 $data->country = '';
1086 $data->isonline = null;
1087 // Get the user picture data - messaging has always shown these to the user.
1088 $userpicture = new \user_picture($user);
1089 $userpicture->size = 1; // Size f1.
1090 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
1091 $userpicture->size = 0; // Size f2.
1092 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
1094 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
1096 if (isset($userfields['city'])) {
1097 $data->city = $userfields['city'];
1099 if (isset($userfields['country'])) {
1100 $data->country = $userfields['country'];
1102 if (isset($userfields['email'])) {
1103 $data->email = $userfields['email'];
1105 if (isset($userfields['lastaccess'])) {
1106 $data->isonline = helper::is_online($userfields['lastaccess']);
1110 $data->isblocked = self::is_blocked($userid, $otheruserid);
1111 $data->iscontact = self::is_contact($userid, $otheruserid);
1117 * Checks if a user can delete messages they have either received or sent.
1119 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1120 * but will still seem as if it was by the user)
1121 * @param int $conversationid The id of the conversation
1122 * @return bool Returns true if a user can delete the conversation, false otherwise.
1124 public static function can_delete_conversation(int $userid, int $conversationid = null) : bool {
1127 if (is_null($conversationid)) {
1128 debugging('\core_message\api::can_delete_conversation() now expects a \'conversationid\' to be passed.',
1133 $systemcontext = \context_system::instance();
1135 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1139 if (!self::is_user_in_conversation($userid, $conversationid)) {
1143 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1144 $USER->id == $userid) {
1152 * Deletes a conversation.
1154 * This function does not verify any permissions.
1156 * @deprecated since 3.6
1157 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1158 * but will still seem as if it was by the user)
1159 * @param int $otheruserid The id of the other user in the conversation
1162 public static function delete_conversation($userid, $otheruserid) {
1163 debugging('\core_message\api::delete_conversation() is deprecated, please use ' .
1164 '\core_message\api::delete_conversation_by_id() instead.', DEBUG_DEVELOPER);
1166 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
1168 // If there is no conversation, there is nothing to do.
1169 if (!$conversationid) {
1173 self::delete_conversation_by_id($userid, $conversationid);
1179 * Deletes a conversation for a specified user.
1181 * This function does not verify any permissions.
1183 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1184 * but will still seem as if it was by the user)
1185 * @param int $conversationid The id of the other user in the conversation
1187 public static function delete_conversation_by_id(int $userid, int $conversationid) {
1190 // Get all messages belonging to this conversation that have not already been deleted by this user.
1193 INNER JOIN {message_conversations} mc
1194 ON m.conversationid = mc.id
1195 LEFT JOIN {message_user_actions} mua
1196 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1197 WHERE mua.id is NULL
1199 ORDER BY m.timecreated ASC";
1200 $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
1202 // Ok, mark these as deleted.
1203 foreach ($messages as $message) {
1204 $mua = new \stdClass();
1205 $mua->userid = $userid;
1206 $mua->messageid = $message->id;
1207 $mua->action = self::MESSAGE_ACTION_DELETED;
1208 $mua->timecreated = time();
1209 $mua->id = $DB->insert_record('message_user_actions', $mua);
1211 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1212 $message->id, $mua->id)->trigger();
1217 * Returns the count of unread conversations (collection of messages from a single user) for
1220 * @param \stdClass $user the user who's conversations should be counted
1221 * @return int the count of the user's unread conversations
1223 public static function count_unread_conversations($user = null) {
1230 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
1232 INNER JOIN {message_conversations} mc
1233 ON m.conversationid = mc.id
1234 INNER JOIN {message_conversation_members} mcm
1235 ON mc.id = mcm.conversationid
1236 LEFT JOIN {message_user_actions} mua
1237 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1238 WHERE mcm.userid = ?
1239 AND mcm.userid != m.useridfrom
1240 AND mua.id is NULL";
1242 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
1246 * Checks if a user can mark all messages as read.
1248 * @param int $userid The user id of who we want to mark the messages for
1249 * @param int $conversationid The id of the conversation
1250 * @return bool true if user is permitted, false otherwise
1253 public static function can_mark_all_messages_as_read(int $userid, int $conversationid) : bool {
1256 $systemcontext = \context_system::instance();
1258 if (has_capability('moodle/site:readallmessages', $systemcontext)) {
1262 if (!self::is_user_in_conversation($userid, $conversationid)) {
1266 if ($USER->id == $userid) {
1274 * Marks all messages being sent to a user in a particular conversation.
1276 * If $conversationdid is null then it marks all messages as read sent to $userid.
1278 * @param int $userid
1279 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
1281 public static function mark_all_messages_as_read($userid, $conversationid = null) {
1284 $messagesql = "SELECT m.*
1286 INNER JOIN {message_conversations} mc
1287 ON mc.id = m.conversationid
1288 INNER JOIN {message_conversation_members} mcm
1289 ON mcm.conversationid = mc.id
1290 LEFT JOIN {message_user_actions} mua
1291 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1292 WHERE mua.id is NULL
1294 AND m.useridfrom != ?";
1295 $messageparams = [];
1296 $messageparams[] = $userid;
1297 $messageparams[] = self::MESSAGE_ACTION_READ;
1298 $messageparams[] = $userid;
1299 $messageparams[] = $userid;
1300 if (!is_null($conversationid)) {
1301 $messagesql .= " AND mc.id = ?";
1302 $messageparams[] = $conversationid;
1305 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
1306 foreach ($messages as $message) {
1307 self::mark_message_as_read($userid, $message);
1313 * Marks all notifications being sent from one user to another user as read.
1315 * If the from user is null then it marks all notifications as read sent to the to user.
1317 * @param int $touserid the id of the message recipient
1318 * @param int|null $fromuserid the id of the message sender, null if all messages
1321 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
1324 $notificationsql = "SELECT n.*
1325 FROM {notifications} n
1327 AND timeread is NULL";
1328 $notificationsparams = [$touserid];
1329 if (!empty($fromuserid)) {
1330 $notificationsql .= " AND useridfrom = ?";
1331 $notificationsparams[] = $fromuserid;
1334 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
1335 foreach ($notifications as $notification) {
1336 self::mark_notification_as_read($notification);
1338 $notifications->close();
1342 * Marks ALL messages being sent from $fromuserid to $touserid as read.
1344 * Can be filtered by type.
1346 * @deprecated since 3.5
1347 * @param int $touserid the id of the message recipient
1348 * @param int $fromuserid the id of the message sender
1349 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
1352 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
1353 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
1354 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
1357 $type = strtolower($type);
1359 $conversationid = null;
1360 $ignoremessages = false;
1361 if (!empty($fromuserid)) {
1362 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
1363 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
1364 $ignoremessages = true;
1368 if (!empty($type)) {
1369 if ($type == MESSAGE_TYPE_NOTIFICATION) {
1370 self::mark_all_notifications_as_read($touserid, $fromuserid);
1371 } else if ($type == MESSAGE_TYPE_MESSAGE) {
1372 if (!$ignoremessages) {
1373 self::mark_all_messages_as_read($touserid, $conversationid);
1376 } else { // We want both.
1377 self::mark_all_notifications_as_read($touserid, $fromuserid);
1378 if (!$ignoremessages) {
1379 self::mark_all_messages_as_read($touserid, $conversationid);
1385 * Returns message preferences.
1387 * @param array $processors
1388 * @param array $providers
1389 * @param \stdClass $user
1393 public static function get_all_message_preferences($processors, $providers, $user) {
1394 $preferences = helper::get_providers_preferences($providers, $user->id);
1395 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
1397 // For every processors put its options on the form (need to get function from processor's lib.php).
1398 foreach ($processors as $processor) {
1399 $processor->object->load_data($preferences, $user->id);
1402 // Load general messaging preferences.
1403 $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
1404 $preferences->mailformat = $user->mailformat;
1405 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
1407 return $preferences;
1411 * Count the number of users blocked by a user.
1413 * @param \stdClass $user The user object
1414 * @return int the number of blocked users
1416 public static function count_blocked_users($user = null) {
1423 $sql = "SELECT count(mub.id)
1424 FROM {message_users_blocked} mub
1425 WHERE mub.userid = :userid";
1426 return $DB->count_records_sql($sql, array('userid' => $user->id));
1430 * Determines if a user is permitted to send another user a private message.
1431 * If no sender is provided then it defaults to the logged in user.
1433 * @param \stdClass $recipient The user object.
1434 * @param \stdClass|null $sender The user object.
1435 * @return bool true if user is permitted, false otherwise.
1437 public static function can_post_message($recipient, $sender = null) {
1440 if (is_null($sender)) {
1441 // The message is from the logged in user, unless otherwise specified.
1445 $systemcontext = \context_system::instance();
1446 if (!has_capability('moodle/site:sendmessage', $systemcontext, $sender)) {
1450 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender->id)) {
1454 // Check if the recipient can be messaged by the sender.
1455 return (self::can_contact_user($recipient->id, $sender->id));
1459 * Determines if a user is permitted to send a message to a given conversation.
1460 * If no sender is provided then it defaults to the logged in user.
1462 * @param int $userid the id of the user on which the checks will be applied.
1463 * @param int $conversationid the id of the conversation we wish to check.
1464 * @return bool true if the user can send a message to the conversation, false otherwise.
1465 * @throws \moodle_exception
1467 public static function can_send_message_to_conversation(int $userid, int $conversationid) : bool {
1470 $systemcontext = \context_system::instance();
1471 if (!has_capability('moodle/site:sendmessage', $systemcontext, $userid)) {
1475 if (!self::is_user_in_conversation($userid, $conversationid)) {
1479 // User can post messages and is in the conversation, but we need to check the conversation type to
1480 // know whether or not to check the user privacy settings via can_contact_user().
1481 $conversation = $DB->get_record('message_conversations', ['id' => $conversationid], '*', MUST_EXIST);
1482 if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
1484 } else if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1485 // Get the other user in the conversation.
1486 $members = self::get_conversation_members($userid, $conversationid);
1487 $otheruser = array_filter($members, function($member) use($userid) {
1488 return $member->id != $userid;
1490 $otheruser = reset($otheruser);
1492 return self::can_contact_user($otheruser->id, $userid);
1494 throw new \moodle_exception("Invalid conversation type '$conversation->type'.");
1499 * Send a message from a user to a conversation.
1501 * This method will create the basic eventdata and delegate to message creation to message_send.
1502 * The message_send() method is responsible for event data that is specific to each recipient.
1504 * @param int $userid the sender id.
1505 * @param int $conversationid the conversation id.
1506 * @param string $message the message to send.
1507 * @param int $format the format of the message to send.
1508 * @return \stdClass the message created.
1509 * @throws \coding_exception
1510 * @throws \moodle_exception if the user is not permitted to send a message to the conversation.
1512 public static function send_message_to_conversation(int $userid, int $conversationid, string $message,
1513 int $format) : \stdClass {
1516 if (!self::can_send_message_to_conversation($userid, $conversationid)) {
1517 throw new \moodle_exception("User $userid cannot send a message to conversation $conversationid");
1520 $eventdata = new \core\message\message();
1521 $eventdata->courseid = 1;
1522 $eventdata->component = 'moodle';
1523 $eventdata->name = 'instantmessage';
1524 $eventdata->userfrom = $userid;
1525 $eventdata->convid = $conversationid;
1527 if ($format == FORMAT_HTML) {
1528 $eventdata->fullmessagehtml = $message;
1529 // Some message processors may revert to sending plain text even if html is supplied,
1530 // so we keep both plain and html versions if we're intending to send html.
1531 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
1533 $eventdata->fullmessage = $message;
1534 $eventdata->fullmessagehtml = '';
1537 $eventdata->fullmessageformat = $format;
1538 $eventdata->smallmessage = $message; // Store the message unfiltered. Clean up on output.
1540 $eventdata->timecreated = time();
1541 $eventdata->notification = 0;
1542 $messageid = message_send($eventdata);
1544 $messagerecord = $DB->get_record('messages', ['id' => $messageid], 'id, useridfrom, fullmessage, timecreated');
1545 $message = (object) [
1546 'id' => $messagerecord->id,
1547 'useridfrom' => $messagerecord->useridfrom,
1548 'text' => $messagerecord->fullmessage,
1549 'timecreated' => $messagerecord->timecreated
1555 * Get the messaging preference for a user.
1556 * If the user has not any messaging privacy preference:
1557 * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
1558 * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
1560 * @param int $userid The user identifier.
1561 * @return int The default messaging preference.
1563 public static function get_user_privacy_messaging_preference(int $userid) : int {
1566 // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
1567 // otherwise, the default value will be "My contacts and anyone in my courses".
1568 if (empty($CFG->messagingallusers)) {
1569 $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
1571 $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
1573 $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $userid);
1575 // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
1576 // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1577 if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
1578 $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
1581 return $privacypreference;
1585 * Checks if the recipient is allowing messages from users that aren't a
1586 * contact. If not then it checks to make sure the sender is in the
1587 * recipient's contacts.
1589 * @deprecated since 3.6
1590 * @param \stdClass $recipient The user object.
1591 * @param \stdClass|null $sender The user object.
1592 * @return bool true if $sender is blocked, false otherwise.
1594 public static function is_user_non_contact_blocked($recipient, $sender = null) {
1595 debugging('\core_message\api::is_user_non_contact_blocked() is deprecated', DEBUG_DEVELOPER);
1599 if (is_null($sender)) {
1600 // The message is from the logged in user, unless otherwise specified.
1604 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1605 switch ($privacypreference) {
1606 case self::MESSAGE_PRIVACY_SITE:
1607 if (!empty($CFG->messagingallusers)) {
1608 // Users can be messaged without being contacts or members of the same course.
1611 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1612 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1613 case self::MESSAGE_PRIVACY_COURSEMEMBER:
1614 // Confirm the sender and the recipient are both members of the same course.
1615 if (enrol_sharing_course($recipient, $sender)) {
1616 // All good, the recipient and the sender are members of the same course.
1619 case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1620 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1621 return !self::is_contact($sender->id, $recipient->id);
1628 * Checks if the recipient has specifically blocked the sending user.
1630 * Note: This function will always return false if the sender has the
1631 * readallmessages capability at the system context level.
1633 * @deprecated since 3.6
1634 * @param int $recipientid User ID of the recipient.
1635 * @param int $senderid User ID of the sender.
1636 * @return bool true if $sender is blocked, false otherwise.
1638 public static function is_user_blocked($recipientid, $senderid = null) {
1639 debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1644 if (is_null($senderid)) {
1645 // The message is from the logged in user, unless otherwise specified.
1646 $senderid = $USER->id;
1649 $systemcontext = \context_system::instance();
1650 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
1654 if (self::is_blocked($recipientid, $senderid)) {
1662 * Get specified message processor, validate corresponding plugin existence and
1663 * system configuration.
1665 * @param string $name Name of the processor.
1666 * @param bool $ready only return ready-to-use processors.
1667 * @return mixed $processor if processor present else empty array.
1670 public static function get_message_processor($name, $ready = false) {
1673 $processor = $DB->get_record('message_processors', array('name' => $name));
1674 if (empty($processor)) {
1675 // Processor not found, return.
1679 $processor = self::get_processed_processor_object($processor);
1681 if ($processor->enabled && $processor->configured) {
1692 * Returns weather a given processor is enabled or not.
1693 * Note:- This doesn't check if the processor is configured or not.
1695 * @param string $name Name of the processor
1698 public static function is_processor_enabled($name) {
1700 $cache = \cache::make('core', 'message_processors_enabled');
1701 $status = $cache->get($name);
1703 if ($status === false) {
1704 $processor = self::get_message_processor($name);
1705 if (!empty($processor)) {
1706 $cache->set($name, $processor->enabled);
1707 return $processor->enabled;
1717 * Set status of a processor.
1719 * @param \stdClass $processor processor record.
1720 * @param 0|1 $enabled 0 or 1 to set the processor status.
1724 public static function update_processor_status($processor, $enabled) {
1726 $cache = \cache::make('core', 'message_processors_enabled');
1727 $cache->delete($processor->name);
1728 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1732 * Given a processor object, loads information about it's settings and configurations.
1733 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1734 * or @see \get_message_processors()
1736 * @param \stdClass $processor processor object
1737 * @return \stdClass processed processor object
1740 public static function get_processed_processor_object(\stdClass $processor) {
1743 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1744 if (is_readable($processorfile)) {
1745 include_once($processorfile);
1746 $processclass = 'message_output_' . $processor->name;
1747 if (class_exists($processclass)) {
1748 $pclass = new $processclass();
1749 $processor->object = $pclass;
1750 $processor->configured = 0;
1751 if ($pclass->is_system_configured()) {
1752 $processor->configured = 1;
1754 $processor->hassettings = 0;
1755 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1756 $processor->hassettings = 1;
1758 $processor->available = 1;
1760 print_error('errorcallingprocessor', 'message');
1763 $processor->available = 0;
1769 * Retrieve users blocked by $user1
1771 * @param int $userid The user id of the user whos blocked users we are returning
1772 * @return array the users blocked
1774 public static function get_blocked_users($userid) {
1777 $userfields = \user_picture::fields('u', array('lastaccess'));
1778 $blockeduserssql = "SELECT $userfields
1779 FROM {message_users_blocked} mub
1781 ON u.id = mub.blockeduserid
1784 GROUP BY $userfields
1785 ORDER BY u.firstname ASC";
1786 return $DB->get_records_sql($blockeduserssql, [$userid]);
1790 * Mark a single message as read.
1792 * @param int $userid The user id who marked the message as read
1793 * @param \stdClass $message The message
1794 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1796 public static function mark_message_as_read($userid, $message, $timeread = null) {
1799 if (is_null($timeread)) {
1803 $mua = new \stdClass();
1804 $mua->userid = $userid;
1805 $mua->messageid = $message->id;
1806 $mua->action = self::MESSAGE_ACTION_READ;
1807 $mua->timecreated = $timeread;
1808 $mua->id = $DB->insert_record('message_user_actions', $mua);
1810 // Get the context for the user who received the message.
1811 $context = \context_user::instance($userid, IGNORE_MISSING);
1812 // If the user no longer exists the context value will be false, in this case use the system context.
1813 if ($context === false) {
1814 $context = \context_system::instance();
1817 // Trigger event for reading a message.
1818 $event = \core\event\message_viewed::create(array(
1819 'objectid' => $mua->id,
1820 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1821 'context' => $context,
1822 'relateduserid' => $message->useridfrom,
1824 'messageid' => $message->id
1831 * Mark a single notification as read.
1833 * @param \stdClass $notification The notification
1834 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1836 public static function mark_notification_as_read($notification, $timeread = null) {
1839 if (is_null($timeread)) {
1843 if (is_null($notification->timeread)) {
1844 $updatenotification = new \stdClass();
1845 $updatenotification->id = $notification->id;
1846 $updatenotification->timeread = $timeread;
1848 $DB->update_record('notifications', $updatenotification);
1850 // Trigger event for reading a notification.
1851 \core\event\notification_viewed::create_from_ids(
1852 $notification->useridfrom,
1853 $notification->useridto,
1860 * Checks if a user can delete a message.
1862 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1863 * but will still seem as if it was by the user)
1864 * @param int $messageid The message id
1865 * @return bool Returns true if a user can delete the message, false otherwise.
1867 public static function can_delete_message($userid, $messageid) {
1870 $systemcontext = \context_system::instance();
1872 $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
1874 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1878 if (!self::is_user_in_conversation($userid, $conversationid)) {
1882 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1883 $USER->id == $userid) {
1891 * Deletes a message.
1893 * This function does not verify any permissions.
1895 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1896 * but will still seem as if it was by the user)
1897 * @param int $messageid The message id
1900 public static function delete_message($userid, $messageid) {
1903 if (!$DB->record_exists('messages', ['id' => $messageid])) {
1907 // Check if the user has already deleted this message.
1908 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1909 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1910 $mua = new \stdClass();
1911 $mua->userid = $userid;
1912 $mua->messageid = $messageid;
1913 $mua->action = self::MESSAGE_ACTION_DELETED;
1914 $mua->timecreated = time();
1915 $mua->id = $DB->insert_record('message_user_actions', $mua);
1917 // Trigger event for deleting a message.
1918 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1919 $messageid, $mua->id)->trigger();
1928 * Returns the conversation between two users.
1930 * @param array $userids
1931 * @return int|bool The id of the conversation, false if not found
1933 public static function get_conversation_between_users(array $userids) {
1936 $hash = helper::get_conversation_hash($userids);
1939 'type' => self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1942 if ($conversation = $DB->get_record('message_conversations', $params)) {
1943 return $conversation->id;
1950 * Creates a conversation between two users.
1952 * @deprecated since 3.6
1953 * @param array $userids
1954 * @return int The id of the conversation
1956 public static function create_conversation_between_users(array $userids) {
1957 debugging('\core_message\api::create_conversation_between_users is deprecated, please use ' .
1958 '\core_message\api::create_conversation instead.', DEBUG_DEVELOPER);
1960 // This method was always used for individual conversations.
1961 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
1963 return $conversation->id;
1967 * Creates a conversation with selected users and messages.
1969 * @param int $type The type of conversation
1970 * @param int[] $userids The array of users to add to the conversation
1971 * @param string|null $name The name of the conversation
1972 * @param int $enabled Determines if the conversation is created enabled or disabled
1973 * @param string|null $component Defines the Moodle component which the conversation belongs to, if any
1974 * @param string|null $itemtype Defines the type of the component
1975 * @param int|null $itemid The id of the component
1976 * @param int|null $contextid The id of the context
1979 public static function create_conversation(int $type, array $userids, string $name = null,
1980 int $enabled = self::MESSAGE_CONVERSATION_ENABLED, string $component = null,
1981 string $itemtype = null, int $itemid = null, int $contextid = null) {
1986 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1987 if (count($userids) > 2) {
1988 throw new \moodle_exception('An individual conversation can not have more than two users.');
1992 $conversation = new \stdClass();
1993 $conversation->type = $type;
1994 $conversation->name = $name;
1995 $conversation->convhash = null;
1996 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1997 $conversation->convhash = helper::get_conversation_hash($userids);
1999 $conversation->component = $component;
2000 $conversation->itemtype = $itemtype;
2001 $conversation->itemid = $itemid;
2002 $conversation->contextid = $contextid;
2003 $conversation->enabled = $enabled;
2004 $conversation->timecreated = time();
2005 $conversation->timemodified = $conversation->timecreated;
2006 $conversation->id = $DB->insert_record('message_conversations', $conversation);
2008 // Add users to this conversation.
2010 foreach ($userids as $userid) {
2011 $member = new \stdClass();
2012 $member->conversationid = $conversation->id;
2013 $member->userid = $userid;
2014 $member->timecreated = time();
2015 $member->id = $DB->insert_record('message_conversation_members', $member);
2017 $arrmembers[] = $member;
2020 $conversation->members = $arrmembers;
2022 return $conversation;
2026 * Checks if a user can create a group conversation.
2028 * @param int $userid The id of the user attempting to create the conversation
2029 * @param \context $context The context they are creating the conversation from, most likely course context
2032 public static function can_create_group_conversation(int $userid, \context $context) : bool {
2035 // If we can't message at all, then we can't create a conversation.
2036 if (empty($CFG->messaging)) {
2040 // We need to check they have the capability to create the conversation.
2041 return has_capability('moodle/course:creategroupconversations', $context, $userid);
2045 * Checks if a user can create a contact request.
2047 * @param int $userid The id of the user who is creating the contact request
2048 * @param int $requesteduserid The id of the user being requested
2051 public static function can_create_contact(int $userid, int $requesteduserid) : bool {
2054 // If we can't message at all, then we can't create a contact.
2055 if (empty($CFG->messaging)) {
2059 // If we can message anyone on the site then we can create a contact.
2060 if ($CFG->messagingallusers) {
2064 // We need to check if they are in the same course.
2065 return enrol_sharing_course($userid, $requesteduserid);
2069 * Handles creating a contact request.
2071 * @param int $userid The id of the user who is creating the contact request
2072 * @param int $requesteduserid The id of the user being requested
2074 public static function create_contact_request(int $userid, int $requesteduserid) {
2077 $request = new \stdClass();
2078 $request->userid = $userid;
2079 $request->requesteduserid = $requesteduserid;
2080 $request->timecreated = time();
2082 $DB->insert_record('message_contact_requests', $request);
2084 // Send a notification.
2085 $userfrom = \core_user::get_user($userid);
2086 $userfromfullname = fullname($userfrom);
2087 $userto = \core_user::get_user($requesteduserid);
2088 $url = new \moodle_url('/message/pendingcontactrequests.php');
2090 $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
2091 $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);
2093 $message = new \core\message\message();
2094 $message->courseid = SITEID;
2095 $message->component = 'moodle';
2096 $message->name = 'messagecontactrequests';
2097 $message->notification = 1;
2098 $message->userfrom = $userfrom;
2099 $message->userto = $userto;
2100 $message->subject = $subject;
2101 $message->fullmessage = text_to_html($fullmessage);
2102 $message->fullmessageformat = FORMAT_HTML;
2103 $message->fullmessagehtml = $fullmessage;
2104 $message->smallmessage = '';
2105 $message->contexturl = $url->out(false);
2107 message_send($message);
2112 * Handles confirming a contact request.
2114 * @param int $userid The id of the user who created the contact request
2115 * @param int $requesteduserid The id of the user confirming the request
2117 public static function confirm_contact_request(int $userid, int $requesteduserid) {
2120 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2121 'requesteduserid' => $requesteduserid])) {
2122 self::add_contact($userid, $requesteduserid);
2124 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2129 * Handles declining a contact request.
2131 * @param int $userid The id of the user who created the contact request
2132 * @param int $requesteduserid The id of the user declining the request
2134 public static function decline_contact_request(int $userid, int $requesteduserid) {
2137 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2138 'requesteduserid' => $requesteduserid])) {
2139 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2144 * Handles returning the contact requests for a user.
2146 * This also includes the user data necessary to display information
2149 * It will not include blocked users.
2151 * @param int $userid
2152 * @param int $limitfrom
2153 * @param int $limitnum
2154 * @return array The list of contact requests
2156 public static function get_contact_requests(int $userid, int $limitfrom = 0, int $limitnum = 0) : array {
2159 $sql = "SELECT mcr.userid
2160 FROM {message_contact_requests} mcr
2161 LEFT JOIN {message_users_blocked} mub
2162 ON (mub.userid = ? AND mub.blockeduserid = mcr.userid)
2163 WHERE mcr.requesteduserid = ?
2165 ORDER BY mcr.timecreated ASC";
2166 if ($contactrequests = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
2167 $userids = array_keys($contactrequests);
2168 return helper::get_member_info($userid, $userids);
2175 * Handles adding a contact.
2177 * @param int $userid The id of the user who requested to be a contact
2178 * @param int $contactid The id of the contact
2180 public static function add_contact(int $userid, int $contactid) {
2183 $messagecontact = new \stdClass();
2184 $messagecontact->userid = $userid;
2185 $messagecontact->contactid = $contactid;
2186 $messagecontact->timecreated = time();
2187 $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
2190 'objectid' => $messagecontact->id,
2191 'userid' => $userid,
2192 'relateduserid' => $contactid,
2193 'context' => \context_user::instance($userid)
2195 $event = \core\event\message_contact_added::create($eventparams);
2196 $event->add_record_snapshot('message_contacts', $messagecontact);
2201 * Handles removing a contact.
2203 * @param int $userid The id of the user who is removing a user as a contact
2204 * @param int $contactid The id of the user to be removed as a contact
2206 public static function remove_contact(int $userid, int $contactid) {
2209 if ($contact = self::get_contact($userid, $contactid)) {
2210 $DB->delete_records('message_contacts', ['id' => $contact->id]);
2212 $event = \core\event\message_contact_removed::create(array(
2213 'objectid' => $contact->id,
2214 'userid' => $userid,
2215 'relateduserid' => $contactid,
2216 'context' => \context_user::instance($userid)
2218 $event->add_record_snapshot('message_contacts', $contact);
2224 * Handles blocking a user.
2226 * @param int $userid The id of the user who is blocking
2227 * @param int $usertoblockid The id of the user being blocked
2229 public static function block_user(int $userid, int $usertoblockid) {
2232 $blocked = new \stdClass();
2233 $blocked->userid = $userid;
2234 $blocked->blockeduserid = $usertoblockid;
2235 $blocked->timecreated = time();
2236 $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
2238 // Trigger event for blocking a contact.
2239 $event = \core\event\message_user_blocked::create(array(
2240 'objectid' => $blocked->id,
2241 'userid' => $userid,
2242 'relateduserid' => $usertoblockid,
2243 'context' => \context_user::instance($userid)
2245 $event->add_record_snapshot('message_users_blocked', $blocked);
2250 * Handles unblocking a user.
2252 * @param int $userid The id of the user who is unblocking
2253 * @param int $usertounblockid The id of the user being unblocked
2255 public static function unblock_user(int $userid, int $usertounblockid) {
2258 if ($blockeduser = $DB->get_record('message_users_blocked',
2259 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
2260 $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
2262 // Trigger event for unblocking a contact.
2263 $event = \core\event\message_user_unblocked::create(array(
2264 'objectid' => $blockeduser->id,
2265 'userid' => $userid,
2266 'relateduserid' => $usertounblockid,
2267 'context' => \context_user::instance($userid)
2269 $event->add_record_snapshot('message_users_blocked', $blockeduser);
2275 * Checks if users are already contacts.
2277 * @param int $userid The id of one of the users
2278 * @param int $contactid The id of the other user
2279 * @return bool Returns true if they are a contact, false otherwise
2281 public static function is_contact(int $userid, int $contactid) : bool {
2285 FROM {message_contacts} mc
2286 WHERE (mc.userid = ? AND mc.contactid = ?)
2287 OR (mc.userid = ? AND mc.contactid = ?)";
2288 return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
2292 * Returns the row in the database table message_contacts that represents the contact between two people.
2294 * @param int $userid The id of one of the users
2295 * @param int $contactid The id of the other user
2296 * @return mixed A fieldset object containing the record, false otherwise
2298 public static function get_contact(int $userid, int $contactid) {
2302 FROM {message_contacts} mc
2303 WHERE (mc.userid = ? AND mc.contactid = ?)
2304 OR (mc.userid = ? AND mc.contactid = ?)";
2305 return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
2309 * Checks if a user is already blocked.
2311 * @param int $userid
2312 * @param int $blockeduserid
2313 * @return bool Returns true if they are a blocked, false otherwise
2315 public static function is_blocked(int $userid, int $blockeduserid) : bool {
2318 return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
2322 * Checks if a contact request already exists between users.
2324 * @param int $userid The id of the user who is creating the contact request
2325 * @param int $requesteduserid The id of the user being requested
2326 * @return bool Returns true if a contact request exists, false otherwise
2328 public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
2332 FROM {message_contact_requests} mcr
2333 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
2334 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
2335 return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
2339 * Checks if a user is already in a conversation.
2341 * @param int $userid The id of the user we want to check if they are in a group
2342 * @param int $conversationid The id of the conversation
2343 * @return bool Returns true if a contact request exists, false otherwise
2345 public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
2348 return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
2349 'userid' => $userid]);
2353 * Checks if the sender can message the recipient.
2355 * @param int $recipientid
2356 * @param int $senderid
2357 * @return bool true if recipient hasn't blocked sender and sender can contact to recipient, false otherwise.
2359 protected static function can_contact_user(int $recipientid, int $senderid) : bool {
2360 if (has_capability('moodle/site:messageanyuser', \context_system::instance(), $senderid)) {
2361 // The sender has the ability to contact any user across the entire site.
2365 // The initial value of $cancontact is null to indicate that a value has not been determined.
2368 if (self::is_blocked($recipientid, $senderid)) {
2369 // The recipient has specifically blocked this sender.
2370 $cancontact = false;
2373 $sharedcourses = null;
2374 if (null === $cancontact) {
2375 // There are three user preference options:
2376 // - Site: Allow anyone not explicitly blocked to contact me;
2377 // - Course members: Allow anyone I am in a course with to contact me; and
2378 // - Contacts: Only allow my contacts to contact me.
2380 // The Site option is only possible when the messagingallusers site setting is also enabled.
2382 $privacypreference = self::get_user_privacy_messaging_preference($recipientid);
2383 if (self::MESSAGE_PRIVACY_SITE === $privacypreference) {
2384 // The user preference is to allow any user to contact them.
2385 // No need to check anything else.
2388 // This user only allows their own contacts, and possibly course peers, to contact them.
2389 // If the users are contacts then we can avoid the more expensive shared courses check.
2390 $cancontact = self::is_contact($senderid, $recipientid);
2392 if (!$cancontact && self::MESSAGE_PRIVACY_COURSEMEMBER === $privacypreference) {
2393 // The users are not contacts and the user allows course member messaging.
2394 // Check whether these two users share any course together.
2395 $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
2396 $cancontact = (!empty($sharedcourses));
2401 if (false === $cancontact) {
2402 // At the moment the users cannot contact one another.
2403 // Check whether the messageanyuser capability applies in any of the shared courses.
2404 // This is intended to allow teachers to message students regardless of message settings.
2406 // Note: You cannot use empty($sharedcourses) here because this may be an empty array.
2407 if (null === $sharedcourses) {
2408 $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
2411 foreach ($sharedcourses as $course) {
2412 // Note: enrol_get_shared_courses will preload any shared context.
2413 if (has_capability('moodle/site:messageanyuser', \context_course::instance($course->id), $senderid)) {
2424 * Add some new members to an existing conversation.
2426 * @param array $userids User ids array to add as members.
2427 * @param int $convid The conversation id. Must exists.
2428 * @throws \dml_missing_record_exception If convid conversation doesn't exist
2429 * @throws \dml_exception If there is a database error
2430 * @throws \moodle_exception If trying to add a member(s) to a non-group conversation
2432 public static function add_members_to_conversation(array $userids, int $convid) {
2435 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2437 // We can only add members to a group conversation.
2438 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2439 throw new \moodle_exception('You can not add members to a non-group conversation.');
2442 // Be sure we are not trying to add a non existing user to the conversation. Work only with existing users.
2443 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2444 $existingusers = $DB->get_fieldset_select('user', 'id', "id $useridcondition", $params);
2446 // Be sure we are not adding a user is already member of the conversation. Take all the members.
2447 $memberuserids = array_values($DB->get_records_menu(
2448 'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
2451 // Work with existing new members.
2453 $newuserids = array_diff($existingusers, $memberuserids);
2454 foreach ($newuserids as $userid) {
2455 $member = new \stdClass();
2456 $member->conversationid = $convid;
2457 $member->userid = $userid;
2458 $member->timecreated = time();
2459 $members[] = $member;
2462 $DB->insert_records('message_conversation_members', $members);
2466 * Remove some members from an existing conversation.
2468 * @param array $userids The user ids to remove from conversation members.
2469 * @param int $convid The conversation id. Must exists.
2470 * @throws \dml_exception
2471 * @throws \moodle_exception If trying to remove a member(s) from a non-group conversation
2473 public static function remove_members_from_conversation(array $userids, int $convid) {
2476 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2478 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2479 throw new \moodle_exception('You can not remove members from a non-group conversation.');
2482 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2483 $params['convid'] = $convid;
2485 $DB->delete_records_select('message_conversation_members',
2486 "conversationid = :convid AND userid $useridcondition", $params);
2490 * Count conversation members.
2492 * @param int $convid The conversation id.
2493 * @return int Number of conversation members.
2494 * @throws \dml_exception
2496 public static function count_conversation_members(int $convid) : int {
2499 return $DB->count_records('message_conversation_members', ['conversationid' => $convid]);
2503 * Checks whether or not a conversation area is enabled.
2505 * @param string $component Defines the Moodle component which the area was added to.
2506 * @param string $itemtype Defines the type of the component.
2507 * @param int $itemid The id of the component.
2508 * @param int $contextid The id of the context.
2509 * @return bool Returns if a conversation area exists and is enabled, false otherwise
2511 public static function is_conversation_area_enabled(string $component, string $itemtype, int $itemid, int $contextid) : bool {
2514 return $DB->record_exists('message_conversations',
2516 'itemid' => $itemid,
2517 'contextid' => $contextid,
2518 'component' => $component,
2519 'itemtype' => $itemtype,
2520 'enabled' => self::MESSAGE_CONVERSATION_ENABLED
2526 * Get conversation by area.
2528 * @param string $component Defines the Moodle component which the area was added to.
2529 * @param string $itemtype Defines the type of the component.
2530 * @param int $itemid The id of the component.
2531 * @param int $contextid The id of the context.
2534 public static function get_conversation_by_area(string $component, string $itemtype, int $itemid, int $contextid) {
2537 return $DB->get_record('message_conversations',
2539 'itemid' => $itemid,
2540 'contextid' => $contextid,
2541 'component' => $component,
2542 'itemtype' => $itemtype
2548 * Enable a conversation.
2550 * @param int $conversationid The id of the conversation.
2553 public static function enable_conversation(int $conversationid) {
2556 $conversation = new \stdClass();
2557 $conversation->id = $conversationid;
2558 $conversation->enabled = self::MESSAGE_CONVERSATION_ENABLED;
2559 $conversation->timemodified = time();
2560 $DB->update_record('message_conversations', $conversation);
2564 * Disable a conversation.
2566 * @param int $conversationid The id of the conversation.
2569 public static function disable_conversation(int $conversationid) {
2572 $conversation = new \stdClass();
2573 $conversation->id = $conversationid;
2574 $conversation->enabled = self::MESSAGE_CONVERSATION_DISABLED;
2575 $conversation->timemodified = time();
2576 $DB->update_record('message_conversations', $conversation);
2580 * Update the name of a conversation.
2582 * @param int $conversationid The id of a conversation.
2583 * @param string $name The main name of the area
2586 public static function update_conversation_name(int $conversationid, string $name) {
2589 if ($conversation = $DB->get_record('message_conversations', array('id' => $conversationid))) {
2590 if ($name <> $conversation->name) {
2591 $conversation->name = $name;
2592 $conversation->timemodified = time();
2593 $DB->update_record('message_conversations', $conversation);
2599 * Returns a list of conversation members.
2601 * @param int $userid The user we are returning the conversation members for, used by helper::get_member_info.
2602 * @param int $conversationid The id of the conversation
2603 * @param bool $includecontactrequests Do we want to include contact requests with this data?
2604 * @param int $limitfrom
2605 * @param int $limitnum
2608 public static function get_conversation_members(int $userid, int $conversationid, bool $includecontactrequests = false,
2609 int $limitfrom = 0, int $limitnum = 0) : array {
2612 if ($members = $DB->get_records('message_conversation_members', ['conversationid' => $conversationid],
2613 'timecreated ASC, id ASC', 'userid', $limitfrom, $limitnum)) {
2614 $userids = array_keys($members);
2615 $members = helper::get_member_info($userid, $userids, $includecontactrequests);