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 // Ok, let's search for contacts first.
223 $sql = "SELECT $ufields, mub.id as isuserblocked
225 JOIN {message_contacts} mc
226 ON u.id = mc.contactid
227 LEFT JOIN {message_users_blocked} mub
228 ON (mub.userid = :userid2 AND mub.blockeduserid = u.id)
229 WHERE mc.userid = :userid
232 AND " . $DB->sql_like($fullname, ':search', false) . "
234 ORDER BY " . $DB->sql_fullname();
235 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'userid2' => $userid,
236 'search' => '%' . $search . '%') + $excludeparams, 0, $limitnum)) {
237 foreach ($users as $user) {
238 $user->blocked = $user->isuserblocked ? 1 : 0;
239 $contacts[] = helper::create_contact($user);
243 // Now, let's get the courses.
244 // Make sure to limit searches to enrolled courses.
245 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
247 // Really we want the user to be able to view the participants if they have the capability
248 // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
249 // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
250 // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
251 if ($arrcourses = \core_course_category::search_courses(array('search' => $search), array('limit' => $limitnum),
252 array('moodle/course:viewparticipants'))) {
253 foreach ($arrcourses as $course) {
254 if (isset($enrolledcourses[$course->id])) {
255 $data = new \stdClass();
256 $data->id = $course->id;
257 $data->shortname = $course->shortname;
258 $data->fullname = $course->fullname;
264 // Let's get those non-contacts. Toast them gears boi.
265 // Note - you can only block contacts, so these users will not be blocked, so no need to get that
266 // extra detail from the database.
267 $noncontacts = array();
268 $sql = "SELECT $ufields
272 AND " . $DB->sql_like($fullname, ':search', false) . "
274 AND u.id NOT IN (SELECT contactid
275 FROM {message_contacts}
276 WHERE userid = :userid)
277 ORDER BY " . $DB->sql_fullname();
278 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
280 foreach ($users as $user) {
281 $noncontacts[] = helper::create_contact($user);
285 return array($contacts, $courses, $noncontacts);
289 * Handles searching for user.
291 * @param int $userid The user id doing the searching
292 * @param string $search The string the user is searching
293 * @param int $limitfrom
294 * @param int $limitnum
297 public static function message_search_users(int $userid, string $search, int $limitfrom = 0, int $limitnum = 20) : array {
300 // Check if messaging is enabled.
301 if (empty($CFG->messaging)) {
302 throw new \moodle_exception('disabled', 'message');
305 // Used to search for contacts.
306 $fullname = $DB->sql_fullname();
308 // Users not to include.
309 $excludeusers = array($userid, $CFG->siteguest);
310 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
312 $params = array('search' => '%' . $search . '%', 'userid1' => $userid, 'userid2' => $userid);
314 // Ok, let's search for contacts first.
317 JOIN {message_contacts} mc
318 ON (u.id = mc.contactid AND mc.userid = :userid1) OR (u.id = mc.userid AND mc.contactid = :userid2)
321 AND " . $DB->sql_like($fullname, ':search', false) . "
323 ORDER BY " . $DB->sql_fullname();
324 $foundusers = $DB->get_records_sql_menu($sql, $params + $excludeparams, $limitfrom, $limitnum);
326 $orderedcontacts = array();
327 if (!empty($foundusers)) {
328 $contacts = helper::get_member_info($userid, array_keys($foundusers));
329 // The get_member_info returns an associative array, so is not ordered in the same way.
330 // We need to reorder it again based on query's result.
331 foreach ($foundusers as $key => $value) {
332 $contact = $contacts[$key];
333 $contact->conversations = self::get_conversations_between_users($userid, $key, 0, 1000);
334 $orderedcontacts[] = $contact;
338 // Let's get those non-contacts.
339 // If site wide messaging is enabled, we just fetch any matched users which are non-contacts.
340 if ($CFG->messagingallusers) {
345 AND " . $DB->sql_like($fullname, ':search', false) . "
347 AND NOT EXISTS (SELECT mc.id
348 FROM {message_contacts} mc
349 WHERE (mc.userid = u.id AND mc.contactid = :userid1)
350 OR (mc.userid = :userid2 AND mc.contactid = u.id))
351 ORDER BY " . $DB->sql_fullname();
353 $foundusers = $DB->get_records_sql($sql, $params + $excludeparams, $limitfrom, $limitnum);
355 require_once($CFG->dirroot . '/user/lib.php');
356 // If site-wide messaging is disabled, then we should only be able to search for users who we are allowed to see.
357 // Because we can't achieve all the required visibility checks in SQL, we'll iterate through the non-contact records
358 // and stop once we have enough matching the 'visible' criteria.
359 // TODO: MDL-63983 - Improve the performance of non-contact searches when site-wide messaging is disabled (default).
361 // Use a local generator to achieve this iteration.
362 $getnoncontactusers = function ($limitfrom = 0, $limitnum = 0) use($fullname, $exclude, $params, $excludeparams) {
368 AND " . $DB->sql_like($fullname, ':search', false) . "
370 AND NOT EXISTS (SELECT mc.id
371 FROM {message_contacts} mc
372 WHERE (mc.userid = u.id AND mc.contactid = :userid1)
373 OR (mc.userid = :userid2 AND mc.contactid = u.id))
374 ORDER BY " . $DB->sql_fullname();
375 while ($records = $DB->get_records_sql($sql, $params + $excludeparams, $limitfrom, $limitnum)) {
377 $limitfrom += $limitnum;
381 // Fetch in batches of $limitnum * 2 to improve the chances of matching a user without going back to the DB.
382 // The generator cannot function without a sensible limiter, so set one if this is not set.
383 $batchlimit = ($limitnum == 0) ? 20 : $limitnum;
385 // We need to make the offset param work with the generator.
386 // Basically, if we want to get say 10 records starting at the 40th record, we need to see 50 records and return only
387 // those after the 40th record. We can never pass the method's offset param to the generator as we need to manage the
388 // position within those valid records ourselves.
389 // See MDL-63983 dealing with performance improvements to this area of code.
390 $noofvalidseenrecords = 0;
392 foreach ($getnoncontactusers(0, $batchlimit) as $users) {
393 foreach ($users as $id => $user) {
394 $userdetails = \user_get_user_details_courses($user);
396 // Return the user only if the searched field is returned.
397 // Otherwise it means that the $USER was not allowed to search the returned user.
398 if (!empty($userdetails) and !empty($userdetails['fullname'])) {
399 // We know we've matched, but only save the record if it's within the offset area we need.
400 if ($limitfrom == 0) {
401 // No offset specified, so just save.
402 $returnedusers[$id] = $user;
404 // There is an offset in play.
405 // If we've passed enough records already (> offset value), then we can save this one.
406 if ($noofvalidseenrecords >= $limitfrom) {
407 $returnedusers[$id] = $user;
410 if (count($returnedusers) == $limitnum) {
413 $noofvalidseenrecords++;
417 $foundusers = $returnedusers;
420 $orderednoncontacts = array();
421 if (!empty($foundusers)) {
422 $noncontacts = helper::get_member_info($userid, array_keys($foundusers));
423 // The get_member_info returns an associative array, so is not ordered in the same way.
424 // We need to reorder it again based on query's result.
425 foreach ($foundusers as $key => $value) {
426 $contact = $noncontacts[$key];
427 $contact->conversations = self::get_conversations_between_users($userid, $key, 0, 1000);
428 $orderednoncontacts[] = $contact;
432 return array($orderedcontacts, $orderednoncontacts);
436 * Gets extra fields, like image url and subname for any conversations linked to components.
438 * The subname is like a subtitle for the conversation, to compliment it's name.
439 * The imageurl is the location of the image for the conversation, as might be seen on a listing of conversations for a user.
441 * @param array $conversations a list of conversations records.
442 * @return array the array of subnames, index by conversation id.
443 * @throws \coding_exception
444 * @throws \dml_exception
446 protected static function get_linked_conversation_extra_fields(array $conversations) : array {
449 $linkedconversations = [];
450 foreach ($conversations as $conversation) {
451 if (!is_null($conversation->component) && !is_null($conversation->itemtype)) {
452 $linkedconversations[$conversation->component][$conversation->itemtype][$conversation->id]
453 = $conversation->itemid;
456 if (empty($linkedconversations)) {
460 // TODO: MDL-63814: Working out the subname for linked conversations should be done in a generic way.
461 // Get the itemid, but only for course group linked conversation for now.
463 if (!empty($linkeditems = $linkedconversations['core_group']['groups'])) { // Format: [conversationid => itemid].
464 // Get the name of the course to which the group belongs.
465 list ($groupidsql, $groupidparams) = $DB->get_in_or_equal(array_values($linkeditems), SQL_PARAMS_NAMED, 'groupid');
466 $sql = "SELECT g.*, c.shortname as courseshortname
470 WHERE g.id $groupidsql";
471 $courseinfo = $DB->get_records_sql($sql, $groupidparams);
472 foreach ($linkeditems as $convid => $groupid) {
473 if (array_key_exists($groupid, $courseinfo)) {
474 $group = $courseinfo[$groupid];
476 $extrafields[$convid]['subname'] = format_string($courseinfo[$groupid]->courseshortname);
479 $extrafields[$convid]['imageurl'] = '';
480 if ($url = get_group_picture_url($group, $group->courseid, true)) {
481 $extrafields[$convid]['imageurl'] = $url->out(false);
491 * Returns the contacts and their conversation to display in the contacts area.
494 * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
495 * to retrieve too much information in a single call will cause performance problems.
498 * This function has specifically been altered to break each of the data sets it
499 * requires into separate database calls. This is to avoid the performance problems
500 * observed when attempting to join large data sets (e.g. the message tables and
503 * While it is possible to gather the data in a single query, and it may even be
504 * more efficient with a correctly tuned database, we have opted to trade off some of
505 * the benefits of a single query in order to ensure this function will work on
506 * most databases with default tunings and with large data sets.
508 * @param int $userid The user id
509 * @param int $limitfrom
510 * @param int $limitnum
511 * @param int $type the type of the conversation, if you wish to filter to a certain type (see api constants).
512 * @param bool $favourites whether to include NO favourites (false) or ONLY favourites (true), or null to ignore this setting.
513 * @return array the array of conversations
514 * @throws \moodle_exception
516 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20, int $type = null,
517 bool $favourites = null) {
520 if (!is_null($type) && !in_array($type, [self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
521 self::MESSAGE_CONVERSATION_TYPE_GROUP])) {
522 throw new \moodle_exception("Invalid value ($type) for type param, please see api constants.");
525 // We need to know which conversations are favourites, so we can either:
526 // 1) Include the 'isfavourite' attribute on conversations (when $favourite = null and we're including all conversations)
527 // 2) Restrict the results to ONLY those conversations which are favourites (when $favourite = true)
528 // 3) Restrict the results to ONLY those conversations which are NOT favourites (when $favourite = false).
529 $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
530 $favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
531 $favouriteconversationids = array_column($favouriteconversations, 'itemid');
532 if ($favourites && empty($favouriteconversationids)) {
533 return []; // If we are aiming to return ONLY favourites, and we have none, there's nothing more to do.
536 // CONVERSATIONS AND MOST RECENT MESSAGE.
537 // Include those conversations with messages first (ordered by most recent message, desc), then add any conversations which
538 // don't have messages, such as newly created group conversations.
539 // Because we're sorting by message 'timecreated', those conversations without messages could be at either the start or the
540 // end of the results (behaviour for sorting of nulls differs between DB vendors), so we use the case to presort these.
542 // If we need to return ONLY favourites, or NO favourites, generate the SQL snippet.
544 $favouriteparams = [];
545 if (null !== $favourites && !empty($favouriteconversationids)) {
546 list ($insql, $favouriteparams) =
547 $DB->get_in_or_equal($favouriteconversationids, SQL_PARAMS_NAMED, 'favouriteids', $favourites);
548 $favouritesql = " AND mc.id {$insql} ";
551 // If we need to restrict type, generate the SQL snippet.
552 $typesql = !is_null($type) ? " AND mc.type = :convtype " : "";
554 $sql = "SELECT m.id as messageid, mc.id as id, mc.name as conversationname, mc.type as conversationtype, m.useridfrom,
555 m.smallmessage, m.fullmessage, m.fullmessageformat, m.fullmessagehtml, m.timecreated, mc.component,
556 mc.itemtype, mc.itemid
557 FROM {message_conversations} mc
558 INNER JOIN {message_conversation_members} mcm
559 ON (mcm.conversationid = mc.id AND mcm.userid = :userid3)
561 SELECT m.conversationid, MAX(m.id) AS messageid
564 SELECT m.conversationid, MAX(m.timecreated) as maxtime
566 INNER JOIN {message_conversation_members} mcm
567 ON mcm.conversationid = m.conversationid
568 LEFT JOIN {message_user_actions} mua
569 ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
571 AND mcm.userid = :userid2
572 GROUP BY m.conversationid
574 ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
575 GROUP BY m.conversationid
577 ON lastmessage.conversationid = mc.id
578 LEFT JOIN {messages} m
579 ON m.id = lastmessage.messageid
580 WHERE mc.id IS NOT NULL $typesql $favouritesql
581 ORDER BY (CASE WHEN m.timecreated IS NULL THEN 0 ELSE 1 END) DESC, m.timecreated DESC, id DESC";
583 $params = array_merge($favouriteparams, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
584 'userid2' => $userid, 'userid3' => $userid, 'convtype' => $type]);
585 $conversationset = $DB->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
589 $individualmembers = [];
591 foreach ($conversationset as $conversation) {
592 $conversations[$conversation->id] = $conversation;
593 $members[$conversation->id] = [];
595 $conversationset->close();
597 // If there are no conversations found, then return early.
598 if (empty($conversations)) {
602 // COMPONENT-LINKED CONVERSATION FIELDS.
603 // Conversations linked to components may have extra information, such as:
604 // - subname: Essentially a subtitle for the conversation. So you'd have "name: subname".
605 // - imageurl: A URL to the image for the linked conversation.
606 // For now, this is ONLY course groups.
607 $convextrafields = self::get_linked_conversation_extra_fields($conversations);
610 // Ideally, we want to get 1 member for each conversation, but this depends on the type and whether there is a recent
613 // For 'individual' type conversations between 2 users, regardless of who sent the last message,
614 // we want the details of the other member in the conversation (i.e. not the current user).
616 // For 'group' type conversations, we want the details of the member who sent the last message, if there is one.
617 // This can be the current user or another group member, but for groups without messages, this will be empty.
619 // This also means that if type filtering is specified and only group conversations are returned, we don't need this extra
620 // query to get the 'other' user as we already have that information.
622 // Work out which members we have already, and which ones we might need to fetch.
623 // If all the last messages were from another user, then we don't need to fetch anything further.
624 foreach ($conversations as $conversation) {
625 if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
626 if (!is_null($conversation->useridfrom) && $conversation->useridfrom != $userid) {
627 $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
628 $individualmembers[$conversation->useridfrom] = $conversation->useridfrom;
630 $individualconversations[] = $conversation->id;
632 } else if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
633 // If we have a recent message, the sender is our member.
634 if (!is_null($conversation->useridfrom)) {
635 $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
636 $groupmembers[$conversation->useridfrom] = $conversation->useridfrom;
640 // If we need to fetch any member information for any of the individual conversations.
641 // This is the case if any of the individual conversations have a recent message sent by the current user.
642 if (!empty($individualconversations)) {
643 list ($icidinsql, $icidinparams) = $DB->get_in_or_equal($individualconversations, SQL_PARAMS_NAMED, 'convid');
644 $indmembersql = "SELECT mcm.id, mcm.conversationid, mcm.userid
645 FROM {message_conversation_members} mcm
646 WHERE mcm.conversationid $icidinsql
647 AND mcm.userid != :userid
649 $indmemberparams = array_merge($icidinparams, ['userid' => $userid]);
650 $conversationmembers = $DB->get_records_sql($indmembersql, $indmemberparams);
652 foreach ($conversationmembers as $mid => $member) {
653 $members[$member->conversationid][$member->userid] = $member->userid;
654 $individualmembers[$member->userid] = $member->userid;
658 // We could fail early here if we're sure that:
659 // a) we have no otherusers for all the conversations (users may have been deleted)
660 // b) we're sure that all conversations are individual (1:1).
662 // We need to pull out the list of users info corresponding to the memberids in the conversations.This
663 // needs to be done in a separate query to avoid doing a join on the messages tables and the user
664 // tables because on large sites these tables are massive which results in extremely slow
665 // performance (typically due to join buffer exhaustion).
666 if (!empty($individualmembers) || !empty($groupmembers)) {
667 // Now, we want to remove any duplicates from the group members array. For individual members we will
668 // be doing a more extensive call as we want their contact requests as well as privacy information,
669 // which is not necessary for group conversations.
670 $diffgroupmembers = array_diff($groupmembers, $individualmembers);
672 $individualmemberinfo = helper::get_member_info($userid, $individualmembers, true, true);
673 $groupmemberinfo = helper::get_member_info($userid, $diffgroupmembers);
675 // Don't use array_merge, as we lose array keys.
676 $memberinfo = $individualmemberinfo + $groupmemberinfo;
678 // Update the members array with the member information.
679 $deletedmembers = [];
680 foreach ($members as $convid => $memberarr) {
681 foreach ($memberarr as $key => $memberid) {
682 if (array_key_exists($memberid, $memberinfo)) {
683 // If the user is deleted, remember that.
684 if ($memberinfo[$memberid]->isdeleted) {
685 $deletedmembers[$convid][] = $memberid;
688 $members[$convid][$key] = clone $memberinfo[$memberid];
690 if ($conversations[$convid]->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
691 // Remove data we don't need for group.
692 $members[$convid][$key]->requirescontact = null;
693 $members[$convid][$key]->canmessage = null;
694 $members[$convid][$key]->contactrequests = [];
702 $cids = array_column($conversations, 'id');
703 list ($cidinsql, $cidinparams) = $DB->get_in_or_equal($cids, SQL_PARAMS_NAMED, 'convid');
704 $membercountsql = "SELECT conversationid, count(id) AS membercount
705 FROM {message_conversation_members} mcm
706 WHERE mcm.conversationid $cidinsql
707 GROUP BY mcm.conversationid";
708 $membercounts = $DB->get_records_sql($membercountsql, $cidinparams);
710 // UNREAD MESSAGE COUNT.
711 // Finally, let's get the unread messages count for this user so that we can add it
712 // to the conversation. Remember we need to ignore the messages the user sent.
713 $unreadcountssql = 'SELECT m.conversationid, count(m.id) as unreadcount
715 INNER JOIN {message_conversations} mc
716 ON mc.id = m.conversationid
717 INNER JOIN {message_conversation_members} mcm
718 ON m.conversationid = mcm.conversationid
719 LEFT JOIN {message_user_actions} mua
720 ON (mua.messageid = m.id AND mua.userid = ? AND
721 (mua.action = ? OR mua.action = ?))
723 AND m.useridfrom != ?
725 GROUP BY m.conversationid';
726 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
729 // Now, create the final return structure.
730 $arrconversations = [];
731 foreach ($conversations as $conversation) {
732 // Do not include any individual conversation which:
733 // a) Contains a deleted member or
734 // b) Does not contain a recent message for the user (this happens if the user has deleted all messages).
735 // Group conversations with deleted users or no messages are always returned.
736 if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL
737 && (isset($deletedmembers[$conversation->id]) || empty($conversation->messageid))) {
741 $conv = new \stdClass();
742 $conv->id = $conversation->id;
743 $conv->name = $conversation->conversationname;
744 $conv->subname = $convextrafields[$conv->id]['subname'] ?? null;
745 $conv->imageurl = $convextrafields[$conv->id]['imageurl'] ?? null;
746 $conv->type = $conversation->conversationtype;
747 $conv->membercount = $membercounts[$conv->id]->membercount;
748 $conv->isfavourite = in_array($conv->id, $favouriteconversationids);
749 $conv->isread = isset($unreadcounts[$conv->id]) ? false : true;
750 $conv->unreadcount = isset($unreadcounts[$conv->id]) ? $unreadcounts[$conv->id]->unreadcount : null;
751 $conv->members = $members[$conv->id];
753 // Add the most recent message information.
754 $conv->messages = [];
755 if ($conversation->smallmessage) {
756 $msg = new \stdClass();
757 $msg->id = $conversation->messageid;
758 $msg->text = message_format_message_text($conversation);
759 $msg->useridfrom = $conversation->useridfrom;
760 $msg->timecreated = $conversation->timecreated;
761 $conv->messages[] = $msg;
764 $arrconversations[] = $conv;
766 return $arrconversations;
770 * Returns all conversations between two users
772 * @param int $userid1 One of the user's id
773 * @param int $userid2 The other user's id
774 * @param int $limitfrom
775 * @param int $limitnum
777 * @throws \dml_exception
779 public static function get_conversations_between_users(int $userid1, int $userid2,
780 int $limitfrom = 0, int $limitnum = 20) : array {
784 if ($userid1 == $userid2) {
788 // Get all conversation where both user1 and user2 are members.
789 // TODO: Add subname value. Waiting for definite table structure.
790 $sql = "SELECT mc.id, mc.type, mc.name, mc.timecreated
791 FROM {message_conversations} mc
792 INNER JOIN {message_conversation_members} mcm1
793 ON mc.id = mcm1.conversationid
794 INNER JOIN {message_conversation_members} mcm2
795 ON mc.id = mcm2.conversationid
796 WHERE mcm1.userid = :userid1
797 AND mcm2.userid = :userid2
799 ORDER BY mc.timecreated DESC";
801 return $DB->get_records_sql($sql, array('userid1' => $userid1, 'userid2' => $userid2), $limitfrom, $limitnum);
805 * Mark a conversation as a favourite for the given user.
807 * @param int $conversationid the id of the conversation to mark as a favourite.
808 * @param int $userid the id of the user to whom the favourite belongs.
809 * @return favourite the favourite object.
810 * @throws \moodle_exception if the user or conversation don't exist.
812 public static function set_favourite_conversation(int $conversationid, int $userid) : favourite {
813 if (!self::is_user_in_conversation($userid, $conversationid)) {
814 throw new \moodle_exception("Conversation doesn't exist or user is not a member");
816 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
817 return $ufservice->create_favourite('core_message', 'message_conversations', $conversationid, \context_system::instance());
821 * Unset a conversation as a favourite for the given user.
823 * @param int $conversationid the id of the conversation to unset as a favourite.
824 * @param int $userid the id to whom the favourite belongs.
825 * @throws \moodle_exception if the favourite does not exist for the user.
827 public static function unset_favourite_conversation(int $conversationid, int $userid) {
828 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
829 $ufservice->delete_favourite('core_message', 'message_conversations', $conversationid, \context_system::instance());
833 * Returns the contacts to display in the contacts area.
835 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
836 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
837 * Followup: MDL-63915
839 * @param int $userid The user id
840 * @param int $limitfrom
841 * @param int $limitnum
844 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
849 FROM {message_contacts} mc
850 WHERE mc.userid = ? OR mc.contactid = ?
851 ORDER BY timecreated DESC";
852 if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
853 foreach ($contacts as $contact) {
854 if ($userid == $contact->userid) {
855 $contactids[] = $contact->contactid;
857 $contactids[] = $contact->userid;
862 if (!empty($contactids)) {
863 list($insql, $inparams) = $DB->get_in_or_equal($contactids);
865 $sql = "SELECT u.*, mub.id as isblocked
867 LEFT JOIN {message_users_blocked} mub
868 ON u.id = mub.blockeduserid
870 if ($contacts = $DB->get_records_sql($sql, $inparams)) {
872 foreach ($contacts as $contact) {
873 $contact->blocked = $contact->isblocked ? 1 : 0;
874 $arrcontacts[] = helper::create_contact($contact);
885 * Returns the an array of the users the given user is in a conversation
886 * with who are a contact and the number of unread messages.
888 * @param int $userid The user id
889 * @param int $limitfrom
890 * @param int $limitnum
893 public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
896 $userfields = \user_picture::fields('u', array('lastaccess'));
897 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
898 FROM {message_contacts} mc
900 ON (u.id = mc.contactid OR u.id = mc.userid)
901 LEFT JOIN {messages} m
902 ON ((m.useridfrom = mc.contactid OR m.useridfrom = mc.userid) AND m.useridfrom != ?)
903 LEFT JOIN {message_conversation_members} mcm
904 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
905 LEFT JOIN {message_user_actions} mua
906 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
907 LEFT JOIN {message_users_blocked} mub
908 ON (mub.userid = ? AND mub.blockeduserid = u.id)
911 AND (mc.userid = ? OR mc.contactid = ?)
914 GROUP BY $userfields";
916 return $DB->get_records_sql($unreadcountssql, [$userid, $userid, $userid, self::MESSAGE_ACTION_READ,
917 $userid, $userid, $userid, $userid], $limitfrom, $limitnum);
921 * Returns the an array of the users the given user is in a conversation
922 * with who are not a contact and the number of unread messages.
924 * @param int $userid The user id
925 * @param int $limitfrom
926 * @param int $limitnum
929 public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
932 $userfields = \user_picture::fields('u', array('lastaccess'));
933 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
935 INNER JOIN {messages} m
936 ON m.useridfrom = u.id
937 INNER JOIN {message_conversation_members} mcm
938 ON mcm.conversationid = m.conversationid
939 LEFT JOIN {message_user_actions} mua
940 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
941 LEFT JOIN {message_contacts} mc
942 ON (mc.userid = ? AND mc.contactid = u.id)
943 LEFT JOIN {message_users_blocked} mub
944 ON (mub.userid = ? AND mub.blockeduserid = u.id)
946 AND mcm.userid != m.useridfrom
951 GROUP BY $userfields";
953 return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
954 $limitfrom, $limitnum);
958 * Returns the messages to display in the message area.
960 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
961 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
962 * Followup: MDL-63915
964 * @param int $userid the current user
965 * @param int $otheruserid the other user
966 * @param int $limitfrom
967 * @param int $limitnum
968 * @param string $sort
969 * @param int $timefrom the time from the message being sent
970 * @param int $timeto the time up until the message being sent
973 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
974 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
976 if (!empty($timefrom)) {
977 // Get the conversation between userid and otheruserid.
978 $userids = [$userid, $otheruserid];
979 if (!$conversationid = self::get_conversation_between_users($userids)) {
980 // This method was always used for individual conversations.
981 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
982 $conversationid = $conversation->id;
985 // Check the cache to see if we even need to do a DB query.
986 $cache = \cache::make('core', 'message_time_last_message_between_users');
987 $key = helper::get_last_message_time_created_cache_key($conversationid);
988 $lastcreated = $cache->get($key);
990 // The last known message time is earlier than the one being requested so we can
991 // just return an empty result set rather than having to query the DB.
992 if ($lastcreated && $lastcreated < $timefrom) {
997 $arrmessages = array();
998 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
999 $sort, $timefrom, $timeto)) {
1000 $arrmessages = helper::create_messages($userid, $messages);
1003 return $arrmessages;
1007 * Returns the messages for the defined conversation.
1009 * @param int $userid The current user.
1010 * @param int $convid The conversation where the messages belong. Could be an object or just the id.
1011 * @param int $limitfrom Return a subset of records, starting at this point (optional).
1012 * @param int $limitnum Return a subset comprising this many records in total (optional, required if $limitfrom is set).
1013 * @param string $sort The column name to order by including optionally direction.
1014 * @param int $timefrom The time from the message being sent.
1015 * @param int $timeto The time up until the message being sent.
1016 * @return array of messages
1018 public static function get_conversation_messages(int $userid, int $convid, int $limitfrom = 0, int $limitnum = 0,
1019 string $sort = 'timecreated ASC', int $timefrom = 0, int $timeto = 0) : array {
1021 if (!empty($timefrom)) {
1022 // Check the cache to see if we even need to do a DB query.
1023 $cache = \cache::make('core', 'message_time_last_message_between_users');
1024 $key = helper::get_last_message_time_created_cache_key($convid);
1025 $lastcreated = $cache->get($key);
1027 // The last known message time is earlier than the one being requested so we can
1028 // just return an empty result set rather than having to query the DB.
1029 if ($lastcreated && $lastcreated < $timefrom) {
1034 $arrmessages = array();
1035 if ($messages = helper::get_conversation_messages($userid, $convid, 0, $limitfrom, $limitnum, $sort, $timefrom, $timeto)) {
1036 $arrmessages = helper::format_conversation_messages($userid, $convid, $messages);
1039 return $arrmessages;
1043 * Returns the most recent message between two users.
1045 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1046 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1047 * Followup: MDL-63915
1049 * @param int $userid the current user
1050 * @param int $otheruserid the other user
1051 * @return \stdClass|null
1053 public static function get_most_recent_message($userid, $otheruserid) {
1054 // We want two messages here so we get an accurate 'blocktime' value.
1055 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
1056 // Swap the order so we now have them in historical order.
1057 $messages = array_reverse($messages);
1058 $arrmessages = helper::create_messages($userid, $messages);
1059 return array_pop($arrmessages);
1066 * Returns the most recent message in a conversation.
1068 * @param int $convid The conversation identifier.
1069 * @param int $currentuserid The current user identifier.
1070 * @return \stdClass|null The most recent message.
1072 public static function get_most_recent_conversation_message(int $convid, int $currentuserid = 0) {
1075 if (empty($currentuserid)) {
1076 $currentuserid = $USER->id;
1079 if ($messages = helper::get_conversation_messages($currentuserid, $convid, 0, 0, 1, 'timecreated DESC')) {
1080 $convmessages = helper::format_conversation_messages($currentuserid, $convid, $messages);
1081 return array_pop($convmessages['messages']);
1088 * Returns the profile information for a contact for a user.
1090 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1091 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1092 * Followup: MDL-63915
1094 * @param int $userid The user id
1095 * @param int $otheruserid The id of the user whose profile we want to view.
1098 public static function get_profile($userid, $otheruserid) {
1101 require_once($CFG->dirroot . '/user/lib.php');
1103 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
1105 // Create the data we are going to pass to the renderable.
1106 $data = new \stdClass();
1107 $data->userid = $otheruserid;
1108 $data->fullname = fullname($user);
1110 $data->country = '';
1112 $data->isonline = null;
1113 // Get the user picture data - messaging has always shown these to the user.
1114 $userpicture = new \user_picture($user);
1115 $userpicture->size = 1; // Size f1.
1116 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
1117 $userpicture->size = 0; // Size f2.
1118 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
1120 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
1122 if (isset($userfields['city'])) {
1123 $data->city = $userfields['city'];
1125 if (isset($userfields['country'])) {
1126 $data->country = $userfields['country'];
1128 if (isset($userfields['email'])) {
1129 $data->email = $userfields['email'];
1131 if (isset($userfields['lastaccess'])) {
1132 $data->isonline = helper::is_online($userfields['lastaccess']);
1136 $data->isblocked = self::is_blocked($userid, $otheruserid);
1137 $data->iscontact = self::is_contact($userid, $otheruserid);
1143 * Checks if a user can delete messages they have either received or sent.
1145 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1146 * but will still seem as if it was by the user)
1147 * @param int $conversationid The id of the conversation
1148 * @return bool Returns true if a user can delete the conversation, false otherwise.
1150 public static function can_delete_conversation(int $userid, int $conversationid = null) : bool {
1153 if (is_null($conversationid)) {
1154 debugging('\core_message\api::can_delete_conversation() now expects a \'conversationid\' to be passed.',
1159 $systemcontext = \context_system::instance();
1161 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1165 if (!self::is_user_in_conversation($userid, $conversationid)) {
1169 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1170 $USER->id == $userid) {
1178 * Deletes a conversation.
1180 * This function does not verify any permissions.
1182 * @deprecated since 3.6
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 $otheruserid The id of the other user in the conversation
1188 public static function delete_conversation($userid, $otheruserid) {
1189 debugging('\core_message\api::delete_conversation() is deprecated, please use ' .
1190 '\core_message\api::delete_conversation_by_id() instead.', DEBUG_DEVELOPER);
1192 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
1194 // If there is no conversation, there is nothing to do.
1195 if (!$conversationid) {
1199 self::delete_conversation_by_id($userid, $conversationid);
1205 * Deletes a conversation for a specified user.
1207 * This function does not verify any permissions.
1209 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1210 * but will still seem as if it was by the user)
1211 * @param int $conversationid The id of the other user in the conversation
1213 public static function delete_conversation_by_id(int $userid, int $conversationid) {
1216 // Get all messages belonging to this conversation that have not already been deleted by this user.
1219 INNER JOIN {message_conversations} mc
1220 ON m.conversationid = mc.id
1221 LEFT JOIN {message_user_actions} mua
1222 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1223 WHERE mua.id is NULL
1225 ORDER BY m.timecreated ASC";
1226 $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
1228 // Ok, mark these as deleted.
1229 foreach ($messages as $message) {
1230 $mua = new \stdClass();
1231 $mua->userid = $userid;
1232 $mua->messageid = $message->id;
1233 $mua->action = self::MESSAGE_ACTION_DELETED;
1234 $mua->timecreated = time();
1235 $mua->id = $DB->insert_record('message_user_actions', $mua);
1237 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1238 $message->id, $mua->id)->trigger();
1243 * Returns the count of unread conversations (collection of messages from a single user) for
1246 * @param \stdClass $user the user who's conversations should be counted
1247 * @return int the count of the user's unread conversations
1249 public static function count_unread_conversations($user = null) {
1256 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
1258 INNER JOIN {message_conversations} mc
1259 ON m.conversationid = mc.id
1260 INNER JOIN {message_conversation_members} mcm
1261 ON mc.id = mcm.conversationid
1262 LEFT JOIN {message_user_actions} mua
1263 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1264 WHERE mcm.userid = ?
1265 AND mcm.userid != m.useridfrom
1266 AND mua.id is NULL";
1268 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
1272 * Checks if a user can mark all messages as read.
1274 * @param int $userid The user id of who we want to mark the messages for
1275 * @param int $conversationid The id of the conversation
1276 * @return bool true if user is permitted, false otherwise
1279 public static function can_mark_all_messages_as_read(int $userid, int $conversationid) : bool {
1282 $systemcontext = \context_system::instance();
1284 if (has_capability('moodle/site:readallmessages', $systemcontext)) {
1288 if (!self::is_user_in_conversation($userid, $conversationid)) {
1292 if ($USER->id == $userid) {
1300 * Marks all messages being sent to a user in a particular conversation.
1302 * If $conversationdid is null then it marks all messages as read sent to $userid.
1304 * @param int $userid
1305 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
1307 public static function mark_all_messages_as_read($userid, $conversationid = null) {
1310 $messagesql = "SELECT m.*
1312 INNER JOIN {message_conversations} mc
1313 ON mc.id = m.conversationid
1314 INNER JOIN {message_conversation_members} mcm
1315 ON mcm.conversationid = mc.id
1316 LEFT JOIN {message_user_actions} mua
1317 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1318 WHERE mua.id is NULL
1320 AND m.useridfrom != ?";
1321 $messageparams = [];
1322 $messageparams[] = $userid;
1323 $messageparams[] = self::MESSAGE_ACTION_READ;
1324 $messageparams[] = $userid;
1325 $messageparams[] = $userid;
1326 if (!is_null($conversationid)) {
1327 $messagesql .= " AND mc.id = ?";
1328 $messageparams[] = $conversationid;
1331 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
1332 foreach ($messages as $message) {
1333 self::mark_message_as_read($userid, $message);
1339 * Marks all notifications being sent from one user to another user as read.
1341 * If the from user is null then it marks all notifications as read sent to the to user.
1343 * @param int $touserid the id of the message recipient
1344 * @param int|null $fromuserid the id of the message sender, null if all messages
1347 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
1350 $notificationsql = "SELECT n.*
1351 FROM {notifications} n
1353 AND timeread is NULL";
1354 $notificationsparams = [$touserid];
1355 if (!empty($fromuserid)) {
1356 $notificationsql .= " AND useridfrom = ?";
1357 $notificationsparams[] = $fromuserid;
1360 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
1361 foreach ($notifications as $notification) {
1362 self::mark_notification_as_read($notification);
1364 $notifications->close();
1368 * Marks ALL messages being sent from $fromuserid to $touserid as read.
1370 * Can be filtered by type.
1372 * @deprecated since 3.5
1373 * @param int $touserid the id of the message recipient
1374 * @param int $fromuserid the id of the message sender
1375 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
1378 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
1379 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
1380 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
1383 $type = strtolower($type);
1385 $conversationid = null;
1386 $ignoremessages = false;
1387 if (!empty($fromuserid)) {
1388 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
1389 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
1390 $ignoremessages = true;
1394 if (!empty($type)) {
1395 if ($type == MESSAGE_TYPE_NOTIFICATION) {
1396 self::mark_all_notifications_as_read($touserid, $fromuserid);
1397 } else if ($type == MESSAGE_TYPE_MESSAGE) {
1398 if (!$ignoremessages) {
1399 self::mark_all_messages_as_read($touserid, $conversationid);
1402 } else { // We want both.
1403 self::mark_all_notifications_as_read($touserid, $fromuserid);
1404 if (!$ignoremessages) {
1405 self::mark_all_messages_as_read($touserid, $conversationid);
1411 * Returns message preferences.
1413 * @param array $processors
1414 * @param array $providers
1415 * @param \stdClass $user
1419 public static function get_all_message_preferences($processors, $providers, $user) {
1420 $preferences = helper::get_providers_preferences($providers, $user->id);
1421 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
1423 // For every processors put its options on the form (need to get function from processor's lib.php).
1424 foreach ($processors as $processor) {
1425 $processor->object->load_data($preferences, $user->id);
1428 // Load general messaging preferences.
1429 $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
1430 $preferences->mailformat = $user->mailformat;
1431 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
1433 return $preferences;
1437 * Count the number of users blocked by a user.
1439 * @param \stdClass $user The user object
1440 * @return int the number of blocked users
1442 public static function count_blocked_users($user = null) {
1449 $sql = "SELECT count(mub.id)
1450 FROM {message_users_blocked} mub
1451 WHERE mub.userid = :userid";
1452 return $DB->count_records_sql($sql, array('userid' => $user->id));
1456 * Determines if a user is permitted to send another user a private message.
1457 * If no sender is provided then it defaults to the logged in user.
1459 * @param \stdClass $recipient The user object.
1460 * @param \stdClass|null $sender The user object.
1461 * @return bool true if user is permitted, false otherwise.
1463 public static function can_post_message($recipient, $sender = null) {
1466 if (is_null($sender)) {
1467 // The message is from the logged in user, unless otherwise specified.
1471 $systemcontext = \context_system::instance();
1472 if (!has_capability('moodle/site:sendmessage', $systemcontext, $sender)) {
1476 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender->id)) {
1480 // Check if the recipient can be messaged by the sender.
1481 return (self::can_contact_user($recipient->id, $sender->id));
1485 * Determines if a user is permitted to send a message to a given conversation.
1486 * If no sender is provided then it defaults to the logged in user.
1488 * @param int $userid the id of the user on which the checks will be applied.
1489 * @param int $conversationid the id of the conversation we wish to check.
1490 * @return bool true if the user can send a message to the conversation, false otherwise.
1491 * @throws \moodle_exception
1493 public static function can_send_message_to_conversation(int $userid, int $conversationid) : bool {
1496 $systemcontext = \context_system::instance();
1497 if (!has_capability('moodle/site:sendmessage', $systemcontext, $userid)) {
1501 if (!self::is_user_in_conversation($userid, $conversationid)) {
1505 // User can post messages and is in the conversation, but we need to check the conversation type to
1506 // know whether or not to check the user privacy settings via can_contact_user().
1507 $conversation = $DB->get_record('message_conversations', ['id' => $conversationid], '*', MUST_EXIST);
1508 if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
1510 } else if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1511 // Get the other user in the conversation.
1512 $members = self::get_conversation_members($userid, $conversationid);
1513 $otheruser = array_filter($members, function($member) use($userid) {
1514 return $member->id != $userid;
1516 $otheruser = reset($otheruser);
1518 return self::can_contact_user($otheruser->id, $userid);
1520 throw new \moodle_exception("Invalid conversation type '$conversation->type'.");
1525 * Send a message from a user to a conversation.
1527 * This method will create the basic eventdata and delegate to message creation to message_send.
1528 * The message_send() method is responsible for event data that is specific to each recipient.
1530 * @param int $userid the sender id.
1531 * @param int $conversationid the conversation id.
1532 * @param string $message the message to send.
1533 * @param int $format the format of the message to send.
1534 * @return \stdClass the message created.
1535 * @throws \coding_exception
1536 * @throws \moodle_exception if the user is not permitted to send a message to the conversation.
1538 public static function send_message_to_conversation(int $userid, int $conversationid, string $message,
1539 int $format) : \stdClass {
1542 if (!self::can_send_message_to_conversation($userid, $conversationid)) {
1543 throw new \moodle_exception("User $userid cannot send a message to conversation $conversationid");
1546 $eventdata = new \core\message\message();
1547 $eventdata->courseid = 1;
1548 $eventdata->component = 'moodle';
1549 $eventdata->name = 'instantmessage';
1550 $eventdata->userfrom = $userid;
1551 $eventdata->convid = $conversationid;
1553 if ($format == FORMAT_HTML) {
1554 $eventdata->fullmessagehtml = $message;
1555 // Some message processors may revert to sending plain text even if html is supplied,
1556 // so we keep both plain and html versions if we're intending to send html.
1557 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
1559 $eventdata->fullmessage = $message;
1560 $eventdata->fullmessagehtml = '';
1563 $eventdata->fullmessageformat = $format;
1564 $eventdata->smallmessage = $message; // Store the message unfiltered. Clean up on output.
1566 $eventdata->timecreated = time();
1567 $eventdata->notification = 0;
1568 $messageid = message_send($eventdata);
1570 $messagerecord = $DB->get_record('messages', ['id' => $messageid], 'id, useridfrom, fullmessage, timecreated');
1571 $message = (object) [
1572 'id' => $messagerecord->id,
1573 'useridfrom' => $messagerecord->useridfrom,
1574 'text' => $messagerecord->fullmessage,
1575 'timecreated' => $messagerecord->timecreated
1581 * Get the messaging preference for a user.
1582 * If the user has not any messaging privacy preference:
1583 * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
1584 * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
1586 * @param int $userid The user identifier.
1587 * @return int The default messaging preference.
1589 public static function get_user_privacy_messaging_preference(int $userid) : int {
1592 // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
1593 // otherwise, the default value will be "My contacts and anyone in my courses".
1594 if (empty($CFG->messagingallusers)) {
1595 $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
1597 $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
1599 $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $userid);
1601 // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
1602 // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1603 if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
1604 $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
1607 return $privacypreference;
1611 * Checks if the recipient is allowing messages from users that aren't a
1612 * contact. If not then it checks to make sure the sender is in the
1613 * recipient's contacts.
1615 * @deprecated since 3.6
1616 * @param \stdClass $recipient The user object.
1617 * @param \stdClass|null $sender The user object.
1618 * @return bool true if $sender is blocked, false otherwise.
1620 public static function is_user_non_contact_blocked($recipient, $sender = null) {
1621 debugging('\core_message\api::is_user_non_contact_blocked() is deprecated', DEBUG_DEVELOPER);
1625 if (is_null($sender)) {
1626 // The message is from the logged in user, unless otherwise specified.
1630 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1631 switch ($privacypreference) {
1632 case self::MESSAGE_PRIVACY_SITE:
1633 if (!empty($CFG->messagingallusers)) {
1634 // Users can be messaged without being contacts or members of the same course.
1637 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1638 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1639 case self::MESSAGE_PRIVACY_COURSEMEMBER:
1640 // Confirm the sender and the recipient are both members of the same course.
1641 if (enrol_sharing_course($recipient, $sender)) {
1642 // All good, the recipient and the sender are members of the same course.
1645 case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1646 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1647 return !self::is_contact($sender->id, $recipient->id);
1654 * Checks if the recipient has specifically blocked the sending user.
1656 * Note: This function will always return false if the sender has the
1657 * readallmessages capability at the system context level.
1659 * @deprecated since 3.6
1660 * @param int $recipientid User ID of the recipient.
1661 * @param int $senderid User ID of the sender.
1662 * @return bool true if $sender is blocked, false otherwise.
1664 public static function is_user_blocked($recipientid, $senderid = null) {
1665 debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1670 if (is_null($senderid)) {
1671 // The message is from the logged in user, unless otherwise specified.
1672 $senderid = $USER->id;
1675 $systemcontext = \context_system::instance();
1676 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
1680 if (self::is_blocked($recipientid, $senderid)) {
1688 * Get specified message processor, validate corresponding plugin existence and
1689 * system configuration.
1691 * @param string $name Name of the processor.
1692 * @param bool $ready only return ready-to-use processors.
1693 * @return mixed $processor if processor present else empty array.
1696 public static function get_message_processor($name, $ready = false) {
1699 $processor = $DB->get_record('message_processors', array('name' => $name));
1700 if (empty($processor)) {
1701 // Processor not found, return.
1705 $processor = self::get_processed_processor_object($processor);
1707 if ($processor->enabled && $processor->configured) {
1718 * Returns weather a given processor is enabled or not.
1719 * Note:- This doesn't check if the processor is configured or not.
1721 * @param string $name Name of the processor
1724 public static function is_processor_enabled($name) {
1726 $cache = \cache::make('core', 'message_processors_enabled');
1727 $status = $cache->get($name);
1729 if ($status === false) {
1730 $processor = self::get_message_processor($name);
1731 if (!empty($processor)) {
1732 $cache->set($name, $processor->enabled);
1733 return $processor->enabled;
1743 * Set status of a processor.
1745 * @param \stdClass $processor processor record.
1746 * @param 0|1 $enabled 0 or 1 to set the processor status.
1750 public static function update_processor_status($processor, $enabled) {
1752 $cache = \cache::make('core', 'message_processors_enabled');
1753 $cache->delete($processor->name);
1754 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1758 * Given a processor object, loads information about it's settings and configurations.
1759 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1760 * or @see \get_message_processors()
1762 * @param \stdClass $processor processor object
1763 * @return \stdClass processed processor object
1766 public static function get_processed_processor_object(\stdClass $processor) {
1769 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1770 if (is_readable($processorfile)) {
1771 include_once($processorfile);
1772 $processclass = 'message_output_' . $processor->name;
1773 if (class_exists($processclass)) {
1774 $pclass = new $processclass();
1775 $processor->object = $pclass;
1776 $processor->configured = 0;
1777 if ($pclass->is_system_configured()) {
1778 $processor->configured = 1;
1780 $processor->hassettings = 0;
1781 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1782 $processor->hassettings = 1;
1784 $processor->available = 1;
1786 print_error('errorcallingprocessor', 'message');
1789 $processor->available = 0;
1795 * Retrieve users blocked by $user1
1797 * @param int $userid The user id of the user whos blocked users we are returning
1798 * @return array the users blocked
1800 public static function get_blocked_users($userid) {
1803 $userfields = \user_picture::fields('u', array('lastaccess'));
1804 $blockeduserssql = "SELECT $userfields
1805 FROM {message_users_blocked} mub
1807 ON u.id = mub.blockeduserid
1810 GROUP BY $userfields
1811 ORDER BY u.firstname ASC";
1812 return $DB->get_records_sql($blockeduserssql, [$userid]);
1816 * Mark a single message as read.
1818 * @param int $userid The user id who marked the message as read
1819 * @param \stdClass $message The message
1820 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1822 public static function mark_message_as_read($userid, $message, $timeread = null) {
1825 if (is_null($timeread)) {
1829 $mua = new \stdClass();
1830 $mua->userid = $userid;
1831 $mua->messageid = $message->id;
1832 $mua->action = self::MESSAGE_ACTION_READ;
1833 $mua->timecreated = $timeread;
1834 $mua->id = $DB->insert_record('message_user_actions', $mua);
1836 // Get the context for the user who received the message.
1837 $context = \context_user::instance($userid, IGNORE_MISSING);
1838 // If the user no longer exists the context value will be false, in this case use the system context.
1839 if ($context === false) {
1840 $context = \context_system::instance();
1843 // Trigger event for reading a message.
1844 $event = \core\event\message_viewed::create(array(
1845 'objectid' => $mua->id,
1846 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1847 'context' => $context,
1848 'relateduserid' => $message->useridfrom,
1850 'messageid' => $message->id
1857 * Mark a single notification as read.
1859 * @param \stdClass $notification The notification
1860 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1862 public static function mark_notification_as_read($notification, $timeread = null) {
1865 if (is_null($timeread)) {
1869 if (is_null($notification->timeread)) {
1870 $updatenotification = new \stdClass();
1871 $updatenotification->id = $notification->id;
1872 $updatenotification->timeread = $timeread;
1874 $DB->update_record('notifications', $updatenotification);
1876 // Trigger event for reading a notification.
1877 \core\event\notification_viewed::create_from_ids(
1878 $notification->useridfrom,
1879 $notification->useridto,
1886 * Checks if a user can delete a message.
1888 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1889 * but will still seem as if it was by the user)
1890 * @param int $messageid The message id
1891 * @return bool Returns true if a user can delete the message, false otherwise.
1893 public static function can_delete_message($userid, $messageid) {
1896 $systemcontext = \context_system::instance();
1898 $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
1900 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1904 if (!self::is_user_in_conversation($userid, $conversationid)) {
1908 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1909 $USER->id == $userid) {
1917 * Deletes a message.
1919 * This function does not verify any permissions.
1921 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1922 * but will still seem as if it was by the user)
1923 * @param int $messageid The message id
1926 public static function delete_message($userid, $messageid) {
1929 if (!$DB->record_exists('messages', ['id' => $messageid])) {
1933 // Check if the user has already deleted this message.
1934 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1935 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1936 $mua = new \stdClass();
1937 $mua->userid = $userid;
1938 $mua->messageid = $messageid;
1939 $mua->action = self::MESSAGE_ACTION_DELETED;
1940 $mua->timecreated = time();
1941 $mua->id = $DB->insert_record('message_user_actions', $mua);
1943 // Trigger event for deleting a message.
1944 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1945 $messageid, $mua->id)->trigger();
1954 * Returns the conversation between two users.
1956 * @param array $userids
1957 * @return int|bool The id of the conversation, false if not found
1959 public static function get_conversation_between_users(array $userids) {
1962 $hash = helper::get_conversation_hash($userids);
1965 'type' => self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1968 if ($conversation = $DB->get_record('message_conversations', $params)) {
1969 return $conversation->id;
1976 * Creates a conversation between two users.
1978 * @deprecated since 3.6
1979 * @param array $userids
1980 * @return int The id of the conversation
1982 public static function create_conversation_between_users(array $userids) {
1983 debugging('\core_message\api::create_conversation_between_users is deprecated, please use ' .
1984 '\core_message\api::create_conversation instead.', DEBUG_DEVELOPER);
1986 // This method was always used for individual conversations.
1987 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
1989 return $conversation->id;
1993 * Creates a conversation with selected users and messages.
1995 * @param int $type The type of conversation
1996 * @param int[] $userids The array of users to add to the conversation
1997 * @param string|null $name The name of the conversation
1998 * @param int $enabled Determines if the conversation is created enabled or disabled
1999 * @param string|null $component Defines the Moodle component which the conversation belongs to, if any
2000 * @param string|null $itemtype Defines the type of the component
2001 * @param int|null $itemid The id of the component
2002 * @param int|null $contextid The id of the context
2005 public static function create_conversation(int $type, array $userids, string $name = null,
2006 int $enabled = self::MESSAGE_CONVERSATION_ENABLED, string $component = null,
2007 string $itemtype = null, int $itemid = null, int $contextid = null) {
2012 self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2013 self::MESSAGE_CONVERSATION_TYPE_GROUP
2016 if (!in_array($type, $validtypes)) {
2017 throw new \moodle_exception('An invalid conversation type was specified.');
2021 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
2022 if (count($userids) > 2) {
2023 throw new \moodle_exception('An individual conversation can not have more than two users.');
2027 $conversation = new \stdClass();
2028 $conversation->type = $type;
2029 $conversation->name = $name;
2030 $conversation->convhash = null;
2031 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
2032 $conversation->convhash = helper::get_conversation_hash($userids);
2034 $conversation->component = $component;
2035 $conversation->itemtype = $itemtype;
2036 $conversation->itemid = $itemid;
2037 $conversation->contextid = $contextid;
2038 $conversation->enabled = $enabled;
2039 $conversation->timecreated = time();
2040 $conversation->timemodified = $conversation->timecreated;
2041 $conversation->id = $DB->insert_record('message_conversations', $conversation);
2043 // Add users to this conversation.
2045 foreach ($userids as $userid) {
2046 $member = new \stdClass();
2047 $member->conversationid = $conversation->id;
2048 $member->userid = $userid;
2049 $member->timecreated = time();
2050 $member->id = $DB->insert_record('message_conversation_members', $member);
2052 $arrmembers[] = $member;
2055 $conversation->members = $arrmembers;
2057 return $conversation;
2061 * Checks if a user can create a group conversation.
2063 * @param int $userid The id of the user attempting to create the conversation
2064 * @param \context $context The context they are creating the conversation from, most likely course context
2067 public static function can_create_group_conversation(int $userid, \context $context) : bool {
2070 // If we can't message at all, then we can't create a conversation.
2071 if (empty($CFG->messaging)) {
2075 // We need to check they have the capability to create the conversation.
2076 return has_capability('moodle/course:creategroupconversations', $context, $userid);
2080 * Checks if a user can create a contact request.
2082 * @param int $userid The id of the user who is creating the contact request
2083 * @param int $requesteduserid The id of the user being requested
2086 public static function can_create_contact(int $userid, int $requesteduserid) : bool {
2089 // If we can't message at all, then we can't create a contact.
2090 if (empty($CFG->messaging)) {
2094 // If we can message anyone on the site then we can create a contact.
2095 if ($CFG->messagingallusers) {
2099 // We need to check if they are in the same course.
2100 return enrol_sharing_course($userid, $requesteduserid);
2104 * Handles creating a contact request.
2106 * @param int $userid The id of the user who is creating the contact request
2107 * @param int $requesteduserid The id of the user being requested
2109 public static function create_contact_request(int $userid, int $requesteduserid) {
2112 $request = new \stdClass();
2113 $request->userid = $userid;
2114 $request->requesteduserid = $requesteduserid;
2115 $request->timecreated = time();
2117 $DB->insert_record('message_contact_requests', $request);
2119 // Send a notification.
2120 $userfrom = \core_user::get_user($userid);
2121 $userfromfullname = fullname($userfrom);
2122 $userto = \core_user::get_user($requesteduserid);
2123 $url = new \moodle_url('/message/pendingcontactrequests.php');
2125 $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
2126 $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);
2128 $message = new \core\message\message();
2129 $message->courseid = SITEID;
2130 $message->component = 'moodle';
2131 $message->name = 'messagecontactrequests';
2132 $message->notification = 1;
2133 $message->userfrom = $userfrom;
2134 $message->userto = $userto;
2135 $message->subject = $subject;
2136 $message->fullmessage = text_to_html($fullmessage);
2137 $message->fullmessageformat = FORMAT_HTML;
2138 $message->fullmessagehtml = $fullmessage;
2139 $message->smallmessage = '';
2140 $message->contexturl = $url->out(false);
2142 message_send($message);
2147 * Handles confirming a contact request.
2149 * @param int $userid The id of the user who created the contact request
2150 * @param int $requesteduserid The id of the user confirming the request
2152 public static function confirm_contact_request(int $userid, int $requesteduserid) {
2155 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2156 'requesteduserid' => $requesteduserid])) {
2157 self::add_contact($userid, $requesteduserid);
2159 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2164 * Handles declining a contact request.
2166 * @param int $userid The id of the user who created the contact request
2167 * @param int $requesteduserid The id of the user declining the request
2169 public static function decline_contact_request(int $userid, int $requesteduserid) {
2172 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2173 'requesteduserid' => $requesteduserid])) {
2174 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2179 * Handles returning the contact requests for a user.
2181 * This also includes the user data necessary to display information
2184 * It will not include blocked users.
2186 * @param int $userid
2187 * @param int $limitfrom
2188 * @param int $limitnum
2189 * @return array The list of contact requests
2191 public static function get_contact_requests(int $userid, int $limitfrom = 0, int $limitnum = 0) : array {
2194 $sql = "SELECT mcr.userid
2195 FROM {message_contact_requests} mcr
2196 LEFT JOIN {message_users_blocked} mub
2197 ON (mub.userid = ? AND mub.blockeduserid = mcr.userid)
2198 WHERE mcr.requesteduserid = ?
2200 ORDER BY mcr.timecreated ASC";
2201 if ($contactrequests = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
2202 $userids = array_keys($contactrequests);
2203 return helper::get_member_info($userid, $userids);
2210 * Handles adding a contact.
2212 * @param int $userid The id of the user who requested to be a contact
2213 * @param int $contactid The id of the contact
2215 public static function add_contact(int $userid, int $contactid) {
2218 $messagecontact = new \stdClass();
2219 $messagecontact->userid = $userid;
2220 $messagecontact->contactid = $contactid;
2221 $messagecontact->timecreated = time();
2222 $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
2225 'objectid' => $messagecontact->id,
2226 'userid' => $userid,
2227 'relateduserid' => $contactid,
2228 'context' => \context_user::instance($userid)
2230 $event = \core\event\message_contact_added::create($eventparams);
2231 $event->add_record_snapshot('message_contacts', $messagecontact);
2236 * Handles removing a contact.
2238 * @param int $userid The id of the user who is removing a user as a contact
2239 * @param int $contactid The id of the user to be removed as a contact
2241 public static function remove_contact(int $userid, int $contactid) {
2244 if ($contact = self::get_contact($userid, $contactid)) {
2245 $DB->delete_records('message_contacts', ['id' => $contact->id]);
2247 $event = \core\event\message_contact_removed::create(array(
2248 'objectid' => $contact->id,
2249 'userid' => $userid,
2250 'relateduserid' => $contactid,
2251 'context' => \context_user::instance($userid)
2253 $event->add_record_snapshot('message_contacts', $contact);
2259 * Handles blocking a user.
2261 * @param int $userid The id of the user who is blocking
2262 * @param int $usertoblockid The id of the user being blocked
2264 public static function block_user(int $userid, int $usertoblockid) {
2267 $blocked = new \stdClass();
2268 $blocked->userid = $userid;
2269 $blocked->blockeduserid = $usertoblockid;
2270 $blocked->timecreated = time();
2271 $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
2273 // Trigger event for blocking a contact.
2274 $event = \core\event\message_user_blocked::create(array(
2275 'objectid' => $blocked->id,
2276 'userid' => $userid,
2277 'relateduserid' => $usertoblockid,
2278 'context' => \context_user::instance($userid)
2280 $event->add_record_snapshot('message_users_blocked', $blocked);
2285 * Handles unblocking a user.
2287 * @param int $userid The id of the user who is unblocking
2288 * @param int $usertounblockid The id of the user being unblocked
2290 public static function unblock_user(int $userid, int $usertounblockid) {
2293 if ($blockeduser = $DB->get_record('message_users_blocked',
2294 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
2295 $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
2297 // Trigger event for unblocking a contact.
2298 $event = \core\event\message_user_unblocked::create(array(
2299 'objectid' => $blockeduser->id,
2300 'userid' => $userid,
2301 'relateduserid' => $usertounblockid,
2302 'context' => \context_user::instance($userid)
2304 $event->add_record_snapshot('message_users_blocked', $blockeduser);
2310 * Checks if users are already contacts.
2312 * @param int $userid The id of one of the users
2313 * @param int $contactid The id of the other user
2314 * @return bool Returns true if they are a contact, false otherwise
2316 public static function is_contact(int $userid, int $contactid) : bool {
2320 FROM {message_contacts} mc
2321 WHERE (mc.userid = ? AND mc.contactid = ?)
2322 OR (mc.userid = ? AND mc.contactid = ?)";
2323 return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
2327 * Returns the row in the database table message_contacts that represents the contact between two people.
2329 * @param int $userid The id of one of the users
2330 * @param int $contactid The id of the other user
2331 * @return mixed A fieldset object containing the record, false otherwise
2333 public static function get_contact(int $userid, int $contactid) {
2337 FROM {message_contacts} mc
2338 WHERE (mc.userid = ? AND mc.contactid = ?)
2339 OR (mc.userid = ? AND mc.contactid = ?)";
2340 return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
2344 * Checks if a user is already blocked.
2346 * @param int $userid
2347 * @param int $blockeduserid
2348 * @return bool Returns true if they are a blocked, false otherwise
2350 public static function is_blocked(int $userid, int $blockeduserid) : bool {
2353 return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
2357 * Checks if a contact request already exists between users.
2359 * @param int $userid The id of the user who is creating the contact request
2360 * @param int $requesteduserid The id of the user being requested
2361 * @return bool Returns true if a contact request exists, false otherwise
2363 public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
2367 FROM {message_contact_requests} mcr
2368 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
2369 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
2370 return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
2374 * Checks if a user is already in a conversation.
2376 * @param int $userid The id of the user we want to check if they are in a group
2377 * @param int $conversationid The id of the conversation
2378 * @return bool Returns true if a contact request exists, false otherwise
2380 public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
2383 return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
2384 'userid' => $userid]);
2388 * Checks if the sender can message the recipient.
2390 * @param int $recipientid
2391 * @param int $senderid
2392 * @return bool true if recipient hasn't blocked sender and sender can contact to recipient, false otherwise.
2394 protected static function can_contact_user(int $recipientid, int $senderid) : bool {
2395 if (has_capability('moodle/site:messageanyuser', \context_system::instance(), $senderid)) {
2396 // The sender has the ability to contact any user across the entire site.
2400 // The initial value of $cancontact is null to indicate that a value has not been determined.
2403 if (self::is_blocked($recipientid, $senderid)) {
2404 // The recipient has specifically blocked this sender.
2405 $cancontact = false;
2408 $sharedcourses = null;
2409 if (null === $cancontact) {
2410 // There are three user preference options:
2411 // - Site: Allow anyone not explicitly blocked to contact me;
2412 // - Course members: Allow anyone I am in a course with to contact me; and
2413 // - Contacts: Only allow my contacts to contact me.
2415 // The Site option is only possible when the messagingallusers site setting is also enabled.
2417 $privacypreference = self::get_user_privacy_messaging_preference($recipientid);
2418 if (self::MESSAGE_PRIVACY_SITE === $privacypreference) {
2419 // The user preference is to allow any user to contact them.
2420 // No need to check anything else.
2423 // This user only allows their own contacts, and possibly course peers, to contact them.
2424 // If the users are contacts then we can avoid the more expensive shared courses check.
2425 $cancontact = self::is_contact($senderid, $recipientid);
2427 if (!$cancontact && self::MESSAGE_PRIVACY_COURSEMEMBER === $privacypreference) {
2428 // The users are not contacts and the user allows course member messaging.
2429 // Check whether these two users share any course together.
2430 $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
2431 $cancontact = (!empty($sharedcourses));
2436 if (false === $cancontact) {
2437 // At the moment the users cannot contact one another.
2438 // Check whether the messageanyuser capability applies in any of the shared courses.
2439 // This is intended to allow teachers to message students regardless of message settings.
2441 // Note: You cannot use empty($sharedcourses) here because this may be an empty array.
2442 if (null === $sharedcourses) {
2443 $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
2446 foreach ($sharedcourses as $course) {
2447 // Note: enrol_get_shared_courses will preload any shared context.
2448 if (has_capability('moodle/site:messageanyuser', \context_course::instance($course->id), $senderid)) {
2459 * Add some new members to an existing conversation.
2461 * @param array $userids User ids array to add as members.
2462 * @param int $convid The conversation id. Must exists.
2463 * @throws \dml_missing_record_exception If convid conversation doesn't exist
2464 * @throws \dml_exception If there is a database error
2465 * @throws \moodle_exception If trying to add a member(s) to a non-group conversation
2467 public static function add_members_to_conversation(array $userids, int $convid) {
2470 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2472 // We can only add members to a group conversation.
2473 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2474 throw new \moodle_exception('You can not add members to a non-group conversation.');
2477 // Be sure we are not trying to add a non existing user to the conversation. Work only with existing users.
2478 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2479 $existingusers = $DB->get_fieldset_select('user', 'id', "id $useridcondition", $params);
2481 // Be sure we are not adding a user is already member of the conversation. Take all the members.
2482 $memberuserids = array_values($DB->get_records_menu(
2483 'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
2486 // Work with existing new members.
2488 $newuserids = array_diff($existingusers, $memberuserids);
2489 foreach ($newuserids as $userid) {
2490 $member = new \stdClass();
2491 $member->conversationid = $convid;
2492 $member->userid = $userid;
2493 $member->timecreated = time();
2494 $members[] = $member;
2497 $DB->insert_records('message_conversation_members', $members);
2501 * Remove some members from an existing conversation.
2503 * @param array $userids The user ids to remove from conversation members.
2504 * @param int $convid The conversation id. Must exists.
2505 * @throws \dml_exception
2506 * @throws \moodle_exception If trying to remove a member(s) from a non-group conversation
2508 public static function remove_members_from_conversation(array $userids, int $convid) {
2511 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2513 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2514 throw new \moodle_exception('You can not remove members from a non-group conversation.');
2517 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2518 $params['convid'] = $convid;
2520 $DB->delete_records_select('message_conversation_members',
2521 "conversationid = :convid AND userid $useridcondition", $params);
2525 * Count conversation members.
2527 * @param int $convid The conversation id.
2528 * @return int Number of conversation members.
2529 * @throws \dml_exception
2531 public static function count_conversation_members(int $convid) : int {
2534 return $DB->count_records('message_conversation_members', ['conversationid' => $convid]);
2538 * Checks whether or not a conversation area is enabled.
2540 * @param string $component Defines the Moodle component which the area was added to.
2541 * @param string $itemtype Defines the type of the component.
2542 * @param int $itemid The id of the component.
2543 * @param int $contextid The id of the context.
2544 * @return bool Returns if a conversation area exists and is enabled, false otherwise
2546 public static function is_conversation_area_enabled(string $component, string $itemtype, int $itemid, int $contextid) : bool {
2549 return $DB->record_exists('message_conversations',
2551 'itemid' => $itemid,
2552 'contextid' => $contextid,
2553 'component' => $component,
2554 'itemtype' => $itemtype,
2555 'enabled' => self::MESSAGE_CONVERSATION_ENABLED
2561 * Get conversation by area.
2563 * @param string $component Defines the Moodle component which the area was added to.
2564 * @param string $itemtype Defines the type of the component.
2565 * @param int $itemid The id of the component.
2566 * @param int $contextid The id of the context.
2569 public static function get_conversation_by_area(string $component, string $itemtype, int $itemid, int $contextid) {
2572 return $DB->get_record('message_conversations',
2574 'itemid' => $itemid,
2575 'contextid' => $contextid,
2576 'component' => $component,
2577 'itemtype' => $itemtype
2583 * Enable a conversation.
2585 * @param int $conversationid The id of the conversation.
2588 public static function enable_conversation(int $conversationid) {
2591 $conversation = new \stdClass();
2592 $conversation->id = $conversationid;
2593 $conversation->enabled = self::MESSAGE_CONVERSATION_ENABLED;
2594 $conversation->timemodified = time();
2595 $DB->update_record('message_conversations', $conversation);
2599 * Disable a conversation.
2601 * @param int $conversationid The id of the conversation.
2604 public static function disable_conversation(int $conversationid) {
2607 $conversation = new \stdClass();
2608 $conversation->id = $conversationid;
2609 $conversation->enabled = self::MESSAGE_CONVERSATION_DISABLED;
2610 $conversation->timemodified = time();
2611 $DB->update_record('message_conversations', $conversation);
2615 * Update the name of a conversation.
2617 * @param int $conversationid The id of a conversation.
2618 * @param string $name The main name of the area
2621 public static function update_conversation_name(int $conversationid, string $name) {
2624 if ($conversation = $DB->get_record('message_conversations', array('id' => $conversationid))) {
2625 if ($name <> $conversation->name) {
2626 $conversation->name = $name;
2627 $conversation->timemodified = time();
2628 $DB->update_record('message_conversations', $conversation);
2634 * Returns a list of conversation members.
2636 * @param int $userid The user we are returning the conversation members for, used by helper::get_member_info.
2637 * @param int $conversationid The id of the conversation
2638 * @param bool $includecontactrequests Do we want to include contact requests with this data?
2639 * @param int $limitfrom
2640 * @param int $limitnum
2643 public static function get_conversation_members(int $userid, int $conversationid, bool $includecontactrequests = false,
2644 int $limitfrom = 0, int $limitnum = 0) : array {
2647 if ($members = $DB->get_records('message_conversation_members', ['conversationid' => $conversationid],
2648 'timecreated ASC, id ASC', 'userid', $limitfrom, $limitnum)) {
2649 $userids = array_keys($members);
2650 $members = helper::get_member_info($userid, $userids, $includecontactrequests);