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 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->dirroot . '/lib/messagelib.php');
32 * Class used to return information to display for the message area.
34 * @copyright 2016 Mark Nelson <markn@moodle.com>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 * The action for reading a message.
42 const MESSAGE_ACTION_READ = 1;
45 * The action for deleting a message.
47 const MESSAGE_ACTION_DELETED = 2;
50 * The privacy setting for being messaged by anyone within courses user is member of.
52 const MESSAGE_PRIVACY_COURSEMEMBER = 0;
55 * The privacy setting for being messaged only by contacts.
57 const MESSAGE_PRIVACY_ONLYCONTACTS = 1;
60 * The privacy setting for being messaged by anyone on the site.
62 const MESSAGE_PRIVACY_SITE = 2;
65 * Handles searching for messages in the message area.
67 * @param int $userid The user id doing the searching
68 * @param string $search The string the user is searching
69 * @param int $limitfrom
70 * @param int $limitnum
73 public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
76 // Get the user fields we want.
77 $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
78 $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
80 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto, m.subject, m.fullmessage, m.fullmessagehtml, m.fullmessageformat,
81 m.smallmessage, m.timecreated, 0 as isread, $ufields, mub.id as userfrom_blocked, $ufields2,
82 mub2.id as userto_blocked
85 ON u.id = m.useridfrom
86 INNER JOIN {message_conversations} mc
87 ON mc.id = m.conversationid
88 INNER JOIN {message_conversation_members} mcm
89 ON mcm.conversationid = m.conversationid
92 LEFT JOIN {message_users_blocked} mub
93 ON (mub.blockeduserid = u.id AND mub.userid = ?)
94 LEFT JOIN {message_users_blocked} mub2
95 ON (mub2.blockeduserid = u2.id AND mub2.userid = ?)
96 LEFT JOIN {message_user_actions} mua
97 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
98 WHERE (m.useridfrom = ? OR mcm.userid = ?)
99 AND m.useridfrom != mcm.userid
103 AND " . $DB->sql_like('smallmessage', '?', false) . "
104 ORDER BY timecreated DESC";
106 $params = array($userid, $userid, $userid, self::MESSAGE_ACTION_DELETED, $userid, $userid, '%' . $search . '%');
108 // Convert the messages into searchable contacts with their last message being the message that was searched.
109 $conversations = array();
110 if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
111 foreach ($messages as $message) {
112 $prefix = 'userfrom_';
113 if ($userid == $message->useridfrom) {
115 // If it from the user, then mark it as read, even if it wasn't by the receiver.
116 $message->isread = true;
118 $blockedcol = $prefix . 'blocked';
119 $message->blocked = $message->$blockedcol ? 1 : 0;
121 $message->messageid = $message->id;
122 $conversations[] = helper::create_contact($message, $prefix);
126 return $conversations;
130 * Handles searching for user in a particular course in the message area.
132 * @param int $userid The user id doing the searching
133 * @param int $courseid The id of the course we are searching in
134 * @param string $search The string the user is searching
135 * @param int $limitfrom
136 * @param int $limitnum
139 public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
142 // Get all the users in the course.
143 list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
144 $sql = "SELECT u.*, mub.id as isblocked
148 LEFT JOIN {message_users_blocked} mub
149 ON (mub.blockeduserid = u.id AND mub.userid = :userid)
150 WHERE u.deleted = 0";
151 // Add more conditions.
152 $fullname = $DB->sql_fullname();
153 $sql .= " AND u.id != :userid2
154 AND " . $DB->sql_like($fullname, ':search', false) . "
155 ORDER BY " . $DB->sql_fullname();
156 $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
158 // Convert all the user records into contacts.
160 if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
161 foreach ($users as $user) {
162 $user->blocked = $user->isblocked ? 1 : 0;
163 $contacts[] = helper::create_contact($user);
171 * Handles searching for user in the message area.
173 * @param int $userid The user id doing the searching
174 * @param string $search The string the user is searching
175 * @param int $limitnum
178 public static function search_users($userid, $search, $limitnum = 0) {
181 // Used to search for contacts.
182 $fullname = $DB->sql_fullname();
183 $ufields = \user_picture::fields('u', array('lastaccess'));
185 // Users not to include.
186 $excludeusers = array($userid, $CFG->siteguest);
187 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
189 // Ok, let's search for contacts first.
191 $sql = "SELECT $ufields, mub.id as isuserblocked
193 JOIN {message_contacts} mc
194 ON u.id = mc.contactid
195 LEFT JOIN {message_users_blocked} mub
196 ON (mub.userid = :userid2 AND mub.blockeduserid = u.id)
197 WHERE mc.userid = :userid
200 AND " . $DB->sql_like($fullname, ':search', false) . "
202 ORDER BY " . $DB->sql_fullname();
203 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'userid2' => $userid,
204 'search' => '%' . $search . '%') + $excludeparams, 0, $limitnum)) {
205 foreach ($users as $user) {
206 $user->blocked = $user->isuserblocked ? 1 : 0;
207 $contacts[] = helper::create_contact($user);
211 // Now, let's get the courses.
212 // Make sure to limit searches to enrolled courses.
213 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
215 // Really we want the user to be able to view the participants if they have the capability
216 // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
217 // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
218 // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
219 if ($arrcourses = \core_course_category::search_courses(array('search' => $search), array('limit' => $limitnum),
220 array('moodle/course:viewparticipants'))) {
221 foreach ($arrcourses as $course) {
222 if (isset($enrolledcourses[$course->id])) {
223 $data = new \stdClass();
224 $data->id = $course->id;
225 $data->shortname = $course->shortname;
226 $data->fullname = $course->fullname;
232 // Let's get those non-contacts. Toast them gears boi.
233 // Note - you can only block contacts, so these users will not be blocked, so no need to get that
234 // extra detail from the database.
235 $noncontacts = array();
236 $sql = "SELECT $ufields
240 AND " . $DB->sql_like($fullname, ':search', false) . "
242 AND u.id NOT IN (SELECT contactid
243 FROM {message_contacts}
244 WHERE userid = :userid)
245 ORDER BY " . $DB->sql_fullname();
246 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
248 foreach ($users as $user) {
249 $noncontacts[] = helper::create_contact($user);
253 return array($contacts, $courses, $noncontacts);
257 * Returns the contacts and their conversation to display in the contacts area.
260 * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
261 * to retrieve too much information in a single call will cause performance problems.
264 * This function has specifically been altered to break each of the data sets it
265 * requires into separate database calls. This is to avoid the performance problems
266 * observed when attempting to join large data sets (e.g. the message tables and
269 * While it is possible to gather the data in a single query, and it may even be
270 * more efficient with a correctly tuned database, we have opted to trade off some of
271 * the benefits of a single query in order to ensure this function will work on
272 * most databases with default tunings and with large data sets.
274 * @param int $userid The user id
275 * @param int $limitfrom
276 * @param int $limitnum
279 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20) {
282 // Get the last message from each conversation that the user belongs to.
283 $sql = "SELECT m.id, m.conversationid, m.useridfrom, mcm2.userid as useridto, m.smallmessage, m.timecreated
286 SELECT MAX(m.id) AS messageid
289 SELECT m.conversationid, MAX(m.timecreated) as maxtime
291 INNER JOIN {message_conversation_members} mcm
292 ON mcm.conversationid = m.conversationid
293 LEFT JOIN {message_user_actions} mua
294 ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
296 AND mcm.userid = :userid2
297 GROUP BY m.conversationid
299 ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
300 GROUP BY m.conversationid
302 ON lastmessage.messageid = m.id
303 INNER JOIN {message_conversation_members} mcm
304 ON mcm.conversationid = m.conversationid
305 INNER JOIN {message_conversation_members} mcm2
306 ON mcm2.conversationid = m.conversationid
307 WHERE mcm.userid = m.useridfrom
308 AND mcm.id != mcm2.id
309 ORDER BY m.timecreated DESC";
310 $messageset = $DB->get_recordset_sql($sql, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
311 'userid2' => $userid], $limitfrom, $limitnum);
314 foreach ($messageset as $message) {
315 $messages[$message->id] = $message;
317 $messageset->close();
319 // If there are no messages return early.
320 if (empty($messages)) {
324 // We need to pull out the list of other users that are part of each of these conversations. This
325 // needs to be done in a separate query to avoid doing a join on the messages tables and the user
326 // tables because on large sites these tables are massive which results in extremely slow
327 // performance (typically due to join buffer exhaustion).
328 $otheruserids = array_map(function($message) use ($userid) {
329 return ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
330 }, array_values($messages));
332 // Ok, let's get the other members in the conversations.
333 list($useridsql, $usersparams) = $DB->get_in_or_equal($otheruserids);
334 $userfields = \user_picture::fields('u', array('lastaccess'));
335 $userssql = "SELECT $userfields
339 $otherusers = $DB->get_records_sql($userssql, $usersparams);
341 // If there are no other users (user may have been deleted), then do not continue.
342 if (empty($otherusers)) {
346 $contactssql = "SELECT contactid
347 FROM {message_contacts}
349 AND contactid $useridsql";
350 $contacts = $DB->get_records_sql($contactssql, array_merge([$userid], $usersparams));
352 // Finally, let's get the unread messages count for this user so that we can add them
353 // to the conversation. Remember we need to ignore the messages the user sent.
354 $unreadcountssql = 'SELECT m.useridfrom, count(m.id) as count
356 INNER JOIN {message_conversations} mc
357 ON mc.id = m.conversationid
358 INNER JOIN {message_conversation_members} mcm
359 ON m.conversationid = mcm.conversationid
360 LEFT JOIN {message_user_actions} mua
361 ON (mua.messageid = m.id AND mua.userid = ? AND
362 (mua.action = ? OR mua.action = ?))
364 AND m.useridfrom != ?
366 GROUP BY useridfrom';
367 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
370 // Get rid of the table prefix.
371 $userfields = str_replace('u.', '', $userfields);
372 $userproperties = explode(',', $userfields);
373 $arrconversations = array();
374 foreach ($messages as $message) {
375 $conversation = new \stdClass();
376 $otheruserid = ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
377 $otheruser = isset($otherusers[$otheruserid]) ? $otherusers[$otheruserid] : null;
378 $contact = isset($contacts[$otheruserid]) ? $contacts[$otheruserid] : null;
380 // It's possible the other user was deleted, so, skip.
381 if (is_null($otheruser)) {
385 // Add the other user's information to the conversation, if we have one.
386 foreach ($userproperties as $prop) {
387 $conversation->$prop = ($otheruser) ? $otheruser->$prop : null;
390 // Add the contact's information, if we have one.
391 $conversation->blocked = ($contact) ? $contact->blocked : null;
393 // Add the message information.
394 $conversation->messageid = $message->id;
395 $conversation->smallmessage = $message->smallmessage;
396 $conversation->useridfrom = $message->useridfrom;
398 // Only consider it unread if $user has unread messages.
399 if (isset($unreadcounts[$otheruserid])) {
400 $conversation->isread = false;
401 $conversation->unreadcount = $unreadcounts[$otheruserid]->count;
403 $conversation->isread = true;
406 $arrconversations[$otheruserid] = helper::create_contact($conversation);
409 return $arrconversations;
413 * Returns the contacts to display in the contacts area.
415 * @param int $userid The user id
416 * @param int $limitfrom
417 * @param int $limitnum
420 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
425 FROM {message_contacts} mc
426 WHERE mc.userid = ? OR mc.contactid = ?
427 ORDER BY timecreated DESC";
428 if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
429 foreach ($contacts as $contact) {
430 if ($userid == $contact->userid) {
431 $contactids[] = $contact->contactid;
433 $contactids[] = $contact->userid;
438 if (!empty($contactids)) {
439 list($insql, $inparams) = $DB->get_in_or_equal($contactids);
441 $sql = "SELECT u.*, mub.id as isblocked
443 LEFT JOIN {message_users_blocked} mub
444 ON u.id = mub.blockeduserid
446 if ($contacts = $DB->get_records_sql($sql, $inparams)) {
448 foreach ($contacts as $contact) {
449 $contact->blocked = $contact->isblocked ? 1 : 0;
450 $arrcontacts[] = helper::create_contact($contact);
461 * Returns the an array of the users the given user is in a conversation
462 * with who are a contact and the number of unread messages.
464 * @param int $userid The user id
465 * @param int $limitfrom
466 * @param int $limitnum
469 public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
472 $userfields = \user_picture::fields('u', array('lastaccess'));
473 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
474 FROM {message_contacts} mc
476 ON (u.id = mc.contactid OR u.id = mc.userid)
477 LEFT JOIN {messages} m
478 ON ((m.useridfrom = mc.contactid OR m.useridfrom = mc.userid) AND m.useridfrom != ?)
479 LEFT JOIN {message_conversation_members} mcm
480 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
481 LEFT JOIN {message_user_actions} mua
482 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
483 LEFT JOIN {message_users_blocked} mub
484 ON (mub.userid = ? AND mub.blockeduserid = u.id)
487 AND (mc.userid = ? OR mc.contactid = ?)
490 GROUP BY $userfields";
492 return $DB->get_records_sql($unreadcountssql, [$userid, $userid, $userid, self::MESSAGE_ACTION_READ,
493 $userid, $userid, $userid, $userid], $limitfrom, $limitnum);
497 * Returns the an array of the users the given user is in a conversation
498 * with who are not a contact and the number of unread messages.
500 * @param int $userid The user id
501 * @param int $limitfrom
502 * @param int $limitnum
505 public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
508 $userfields = \user_picture::fields('u', array('lastaccess'));
509 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
511 INNER JOIN {messages} m
512 ON m.useridfrom = u.id
513 INNER JOIN {message_conversation_members} mcm
514 ON mcm.conversationid = m.conversationid
515 LEFT JOIN {message_user_actions} mua
516 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
517 LEFT JOIN {message_contacts} mc
518 ON (mc.userid = ? AND mc.contactid = u.id)
519 LEFT JOIN {message_users_blocked} mub
520 ON (mub.userid = ? AND mub.blockeduserid = u.id)
522 AND mcm.userid != m.useridfrom
527 GROUP BY $userfields";
529 return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
530 $limitfrom, $limitnum);
534 * Returns the messages to display in the message area.
536 * @param int $userid the current user
537 * @param int $otheruserid the other user
538 * @param int $limitfrom
539 * @param int $limitnum
540 * @param string $sort
541 * @param int $timefrom the time from the message being sent
542 * @param int $timeto the time up until the message being sent
545 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
546 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
548 if (!empty($timefrom)) {
549 // Check the cache to see if we even need to do a DB query.
550 $cache = \cache::make('core', 'message_time_last_message_between_users');
551 $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
552 $lastcreated = $cache->get($key);
554 // The last known message time is earlier than the one being requested so we can
555 // just return an empty result set rather than having to query the DB.
556 if ($lastcreated && $lastcreated < $timefrom) {
561 $arrmessages = array();
562 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
563 $sort, $timefrom, $timeto)) {
565 $arrmessages = helper::create_messages($userid, $messages);
572 * Returns the most recent message between two users.
574 * @param int $userid the current user
575 * @param int $otheruserid the other user
576 * @return \stdClass|null
578 public static function get_most_recent_message($userid, $otheruserid) {
579 // We want two messages here so we get an accurate 'blocktime' value.
580 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
581 // Swap the order so we now have them in historical order.
582 $messages = array_reverse($messages);
583 $arrmessages = helper::create_messages($userid, $messages);
584 return array_pop($arrmessages);
591 * Returns the profile information for a contact for a user.
593 * @param int $userid The user id
594 * @param int $otheruserid The id of the user whose profile we want to view.
597 public static function get_profile($userid, $otheruserid) {
600 require_once($CFG->dirroot . '/user/lib.php');
602 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
604 // Create the data we are going to pass to the renderable.
605 $data = new \stdClass();
606 $data->userid = $otheruserid;
607 $data->fullname = fullname($user);
611 $data->isonline = null;
612 // Get the user picture data - messaging has always shown these to the user.
613 $userpicture = new \user_picture($user);
614 $userpicture->size = 1; // Size f1.
615 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
616 $userpicture->size = 0; // Size f2.
617 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
619 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
621 if (isset($userfields['city'])) {
622 $data->city = $userfields['city'];
624 if (isset($userfields['country'])) {
625 $data->country = $userfields['country'];
627 if (isset($userfields['email'])) {
628 $data->email = $userfields['email'];
630 if (isset($userfields['lastaccess'])) {
631 $data->isonline = helper::is_online($userfields['lastaccess']);
635 $data->isblocked = self::is_blocked($userid, $otheruserid);
636 $data->iscontact = self::is_contact($userid, $otheruserid);
642 * Checks if a user can delete messages they have either received or sent.
644 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
645 * but will still seem as if it was by the user)
646 * @param int $conversationid The id of the conversation
647 * @return bool Returns true if a user can delete the conversation, false otherwise.
649 public static function can_delete_conversation(int $userid, int $conversationid = null) : bool {
652 if (is_null($conversationid)) {
653 debugging('\core_message\api::can_delete_conversation() now expects a \'conversationid\' to be passed.',
658 $systemcontext = \context_system::instance();
660 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
664 if (!self::is_user_in_conversation($userid, $conversationid)) {
668 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
669 $USER->id == $userid) {
677 * Deletes a conversation.
679 * This function does not verify any permissions.
681 * @deprecated since 3.6
682 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
683 * but will still seem as if it was by the user)
684 * @param int $otheruserid The id of the other user in the conversation
687 public static function delete_conversation($userid, $otheruserid) {
688 debugging('\core_message\api::delete_conversation() is deprecated, please use ' .
689 '\core_message\api::delete_conversation_by_id() instead.', DEBUG_DEVELOPER);
691 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
693 // If there is no conversation, there is nothing to do.
694 if (!$conversationid) {
698 self::delete_conversation_by_id($userid, $conversationid);
704 * Deletes a conversation for a specified user.
706 * This function does not verify any permissions.
708 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
709 * but will still seem as if it was by the user)
710 * @param int $conversationid The id of the other user in the conversation
712 public static function delete_conversation_by_id(int $userid, int $conversationid) {
715 // Get all messages belonging to this conversation that have not already been deleted by this user.
718 INNER JOIN {message_conversations} mc
719 ON m.conversationid = mc.id
720 LEFT JOIN {message_user_actions} mua
721 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
724 ORDER BY m.timecreated ASC";
725 $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
727 // Ok, mark these as deleted.
728 foreach ($messages as $message) {
729 $mua = new \stdClass();
730 $mua->userid = $userid;
731 $mua->messageid = $message->id;
732 $mua->action = self::MESSAGE_ACTION_DELETED;
733 $mua->timecreated = time();
734 $mua->id = $DB->insert_record('message_user_actions', $mua);
736 \core\event\message_deleted::create_from_ids($userid, $USER->id,
737 $message->id, $mua->id)->trigger();
742 * Returns the count of unread conversations (collection of messages from a single user) for
745 * @param \stdClass $user the user who's conversations should be counted
746 * @return int the count of the user's unread conversations
748 public static function count_unread_conversations($user = null) {
755 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
757 INNER JOIN {message_conversations} mc
758 ON m.conversationid = mc.id
759 INNER JOIN {message_conversation_members} mcm
760 ON mc.id = mcm.conversationid
761 LEFT JOIN {message_user_actions} mua
762 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
764 AND mcm.userid != m.useridfrom
767 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
771 * Marks all messages being sent to a user in a particular conversation.
773 * If $conversationdid is null then it marks all messages as read sent to $userid.
776 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
778 public static function mark_all_messages_as_read($userid, $conversationid = null) {
781 $messagesql = "SELECT m.*
783 INNER JOIN {message_conversations} mc
784 ON mc.id = m.conversationid
785 INNER JOIN {message_conversation_members} mcm
786 ON mcm.conversationid = mc.id
787 LEFT JOIN {message_user_actions} mua
788 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
791 AND m.useridfrom != ?";
793 $messageparams[] = $userid;
794 $messageparams[] = self::MESSAGE_ACTION_READ;
795 $messageparams[] = $userid;
796 $messageparams[] = $userid;
797 if (!is_null($conversationid)) {
798 $messagesql .= " AND mc.id = ?";
799 $messageparams[] = $conversationid;
802 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
803 foreach ($messages as $message) {
804 self::mark_message_as_read($userid, $message);
810 * Marks all notifications being sent from one user to another user as read.
812 * If the from user is null then it marks all notifications as read sent to the to user.
814 * @param int $touserid the id of the message recipient
815 * @param int|null $fromuserid the id of the message sender, null if all messages
818 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
821 $notificationsql = "SELECT n.*
822 FROM {notifications} n
824 AND timeread is NULL";
825 $notificationsparams = [$touserid];
826 if (!empty($fromuserid)) {
827 $notificationsql .= " AND useridfrom = ?";
828 $notificationsparams[] = $fromuserid;
831 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
832 foreach ($notifications as $notification) {
833 self::mark_notification_as_read($notification);
835 $notifications->close();
839 * Marks ALL messages being sent from $fromuserid to $touserid as read.
841 * Can be filtered by type.
843 * @deprecated since 3.5
844 * @param int $touserid the id of the message recipient
845 * @param int $fromuserid the id of the message sender
846 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
849 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
850 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
851 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
854 $type = strtolower($type);
856 $conversationid = null;
857 $ignoremessages = false;
858 if (!empty($fromuserid)) {
859 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
860 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
861 $ignoremessages = true;
866 if ($type == MESSAGE_TYPE_NOTIFICATION) {
867 self::mark_all_notifications_as_read($touserid, $fromuserid);
868 } else if ($type == MESSAGE_TYPE_MESSAGE) {
869 if (!$ignoremessages) {
870 self::mark_all_messages_as_read($touserid, $conversationid);
873 } else { // We want both.
874 self::mark_all_notifications_as_read($touserid, $fromuserid);
875 if (!$ignoremessages) {
876 self::mark_all_messages_as_read($touserid, $conversationid);
882 * Returns message preferences.
884 * @param array $processors
885 * @param array $providers
886 * @param \stdClass $user
890 public static function get_all_message_preferences($processors, $providers, $user) {
891 $preferences = helper::get_providers_preferences($providers, $user->id);
892 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
894 // For every processors put its options on the form (need to get function from processor's lib.php).
895 foreach ($processors as $processor) {
896 $processor->object->load_data($preferences, $user->id);
899 // Load general messaging preferences.
900 $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
901 $preferences->mailformat = $user->mailformat;
902 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
908 * Count the number of users blocked by a user.
910 * @param \stdClass $user The user object
911 * @return int the number of blocked users
913 public static function count_blocked_users($user = null) {
920 $sql = "SELECT count(mub.id)
921 FROM {message_users_blocked} mub
922 WHERE mub.userid = :userid";
923 return $DB->count_records_sql($sql, array('userid' => $user->id));
927 * Determines if a user is permitted to send another user a private message.
928 * If no sender is provided then it defaults to the logged in user.
930 * @param \stdClass $recipient The user object.
931 * @param \stdClass|null $sender The user object.
932 * @return bool true if user is permitted, false otherwise.
934 public static function can_post_message($recipient, $sender = null) {
937 if (is_null($sender)) {
938 // The message is from the logged in user, unless otherwise specified.
942 if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
946 // The recipient blocks messages from non-contacts and the
947 // sender isn't a contact.
948 if (self::is_user_non_contact_blocked($recipient, $sender)) {
953 if ($sender !== null && isset($sender->id)) {
954 $senderid = $sender->id;
957 $systemcontext = \context_system::instance();
958 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
962 // The recipient has specifically blocked this sender.
963 if (self::is_blocked($recipient->id, $senderid)) {
971 * Get the messaging preference for a user.
972 * If the user has not any messaging privacy preference:
973 * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
974 * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
976 * @param int $userid The user identifier.
977 * @return int The default messaging preference.
979 public static function get_user_privacy_messaging_preference(int $userid) : int {
982 // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
983 // otherwise, the default value will be "My contacts and anyone in my courses".
984 if (empty($CFG->messagingallusers)) {
985 $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
987 $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
989 $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $userid);
991 // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
992 // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
993 if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
994 $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
997 return $privacypreference;
1001 * Checks if the recipient is allowing messages from users that aren't a
1002 * contact. If not then it checks to make sure the sender is in the
1003 * recipient's contacts.
1005 * @param \stdClass $recipient The user object.
1006 * @param \stdClass|null $sender The user object.
1007 * @return bool true if $sender is blocked, false otherwise.
1009 public static function is_user_non_contact_blocked($recipient, $sender = null) {
1012 if (is_null($sender)) {
1013 // The message is from the logged in user, unless otherwise specified.
1017 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1018 switch ($privacypreference) {
1019 case self::MESSAGE_PRIVACY_SITE:
1020 if (!empty($CFG->messagingallusers)) {
1021 // Users can be messaged without being contacts or members of the same course.
1024 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1025 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1026 case self::MESSAGE_PRIVACY_COURSEMEMBER:
1027 // Confirm the sender and the recipient are both members of the same course.
1028 if (enrol_sharing_course($recipient, $sender)) {
1029 // All good, the recipient and the sender are members of the same course.
1032 case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1033 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1034 return !self::is_contact($sender->id, $recipient->id);
1041 * Checks if the recipient has specifically blocked the sending user.
1043 * Note: This function will always return false if the sender has the
1044 * readallmessages capability at the system context level.
1046 * @deprecated since 3.6
1047 * @param int $recipientid User ID of the recipient.
1048 * @param int $senderid User ID of the sender.
1049 * @return bool true if $sender is blocked, false otherwise.
1051 public static function is_user_blocked($recipientid, $senderid = null) {
1052 debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1057 if (is_null($senderid)) {
1058 // The message is from the logged in user, unless otherwise specified.
1059 $senderid = $USER->id;
1062 $systemcontext = \context_system::instance();
1063 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
1067 if (self::is_blocked($recipientid, $senderid)) {
1075 * Get specified message processor, validate corresponding plugin existence and
1076 * system configuration.
1078 * @param string $name Name of the processor.
1079 * @param bool $ready only return ready-to-use processors.
1080 * @return mixed $processor if processor present else empty array.
1083 public static function get_message_processor($name, $ready = false) {
1086 $processor = $DB->get_record('message_processors', array('name' => $name));
1087 if (empty($processor)) {
1088 // Processor not found, return.
1092 $processor = self::get_processed_processor_object($processor);
1094 if ($processor->enabled && $processor->configured) {
1105 * Returns weather a given processor is enabled or not.
1106 * Note:- This doesn't check if the processor is configured or not.
1108 * @param string $name Name of the processor
1111 public static function is_processor_enabled($name) {
1113 $cache = \cache::make('core', 'message_processors_enabled');
1114 $status = $cache->get($name);
1116 if ($status === false) {
1117 $processor = self::get_message_processor($name);
1118 if (!empty($processor)) {
1119 $cache->set($name, $processor->enabled);
1120 return $processor->enabled;
1130 * Set status of a processor.
1132 * @param \stdClass $processor processor record.
1133 * @param 0|1 $enabled 0 or 1 to set the processor status.
1137 public static function update_processor_status($processor, $enabled) {
1139 $cache = \cache::make('core', 'message_processors_enabled');
1140 $cache->delete($processor->name);
1141 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1145 * Given a processor object, loads information about it's settings and configurations.
1146 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1147 * or @see \get_message_processors()
1149 * @param \stdClass $processor processor object
1150 * @return \stdClass processed processor object
1153 public static function get_processed_processor_object(\stdClass $processor) {
1156 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1157 if (is_readable($processorfile)) {
1158 include_once($processorfile);
1159 $processclass = 'message_output_' . $processor->name;
1160 if (class_exists($processclass)) {
1161 $pclass = new $processclass();
1162 $processor->object = $pclass;
1163 $processor->configured = 0;
1164 if ($pclass->is_system_configured()) {
1165 $processor->configured = 1;
1167 $processor->hassettings = 0;
1168 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1169 $processor->hassettings = 1;
1171 $processor->available = 1;
1173 print_error('errorcallingprocessor', 'message');
1176 $processor->available = 0;
1182 * Retrieve users blocked by $user1
1184 * @param int $userid The user id of the user whos blocked users we are returning
1185 * @return array the users blocked
1187 public static function get_blocked_users($userid) {
1190 $userfields = \user_picture::fields('u', array('lastaccess'));
1191 $blockeduserssql = "SELECT $userfields
1192 FROM {message_users_blocked} mub
1194 ON u.id = mub.blockeduserid
1197 GROUP BY $userfields
1198 ORDER BY u.firstname ASC";
1199 return $DB->get_records_sql($blockeduserssql, [$userid]);
1203 * Mark a single message as read.
1205 * @param int $userid The user id who marked the message as read
1206 * @param \stdClass $message The message
1207 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1209 public static function mark_message_as_read($userid, $message, $timeread = null) {
1212 if (is_null($timeread)) {
1216 $mua = new \stdClass();
1217 $mua->userid = $userid;
1218 $mua->messageid = $message->id;
1219 $mua->action = self::MESSAGE_ACTION_READ;
1220 $mua->timecreated = $timeread;
1221 $mua->id = $DB->insert_record('message_user_actions', $mua);
1223 // Get the context for the user who received the message.
1224 $context = \context_user::instance($userid, IGNORE_MISSING);
1225 // If the user no longer exists the context value will be false, in this case use the system context.
1226 if ($context === false) {
1227 $context = \context_system::instance();
1230 // Trigger event for reading a message.
1231 $event = \core\event\message_viewed::create(array(
1232 'objectid' => $mua->id,
1233 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1234 'context' => $context,
1235 'relateduserid' => $message->useridfrom,
1237 'messageid' => $message->id
1244 * Mark a single notification as read.
1246 * @param \stdClass $notification The notification
1247 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1249 public static function mark_notification_as_read($notification, $timeread = null) {
1252 if (is_null($timeread)) {
1256 if (is_null($notification->timeread)) {
1257 $updatenotification = new \stdClass();
1258 $updatenotification->id = $notification->id;
1259 $updatenotification->timeread = $timeread;
1261 $DB->update_record('notifications', $updatenotification);
1263 // Trigger event for reading a notification.
1264 \core\event\notification_viewed::create_from_ids(
1265 $notification->useridfrom,
1266 $notification->useridto,
1273 * Checks if a user can delete a message.
1275 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1276 * but will still seem as if it was by the user)
1277 * @param int $messageid The message id
1278 * @return bool Returns true if a user can delete the message, false otherwise.
1280 public static function can_delete_message($userid, $messageid) {
1283 $systemcontext = \context_system::instance();
1285 $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
1287 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1291 if (!self::is_user_in_conversation($userid, $conversationid)) {
1295 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1296 $USER->id == $userid) {
1304 * Deletes a message.
1306 * This function does not verify any permissions.
1308 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1309 * but will still seem as if it was by the user)
1310 * @param int $messageid The message id
1313 public static function delete_message($userid, $messageid) {
1316 if (!$DB->record_exists('messages', ['id' => $messageid])) {
1320 // Check if the user has already deleted this message.
1321 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1322 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1323 $mua = new \stdClass();
1324 $mua->userid = $userid;
1325 $mua->messageid = $messageid;
1326 $mua->action = self::MESSAGE_ACTION_DELETED;
1327 $mua->timecreated = time();
1328 $mua->id = $DB->insert_record('message_user_actions', $mua);
1330 // Trigger event for deleting a message.
1331 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1332 $messageid, $mua->id)->trigger();
1341 * Returns the conversation between two users.
1343 * @param array $userids
1344 * @return int|bool The id of the conversation, false if not found
1346 public static function get_conversation_between_users(array $userids) {
1349 $hash = helper::get_conversation_hash($userids);
1351 if ($conversation = $DB->get_record('message_conversations', ['convhash' => $hash])) {
1352 return $conversation->id;
1359 * Creates a conversation between two users.
1361 * @param array $userids
1362 * @return int The id of the conversation
1364 public static function create_conversation_between_users(array $userids) {
1367 $conversation = new \stdClass();
1368 $conversation->convhash = helper::get_conversation_hash($userids);
1369 $conversation->timecreated = time();
1370 $conversation->id = $DB->insert_record('message_conversations', $conversation);
1372 // Add members to this conversation.
1373 foreach ($userids as $userid) {
1374 $member = new \stdClass();
1375 $member->conversationid = $conversation->id;
1376 $member->userid = $userid;
1377 $member->timecreated = time();
1378 $DB->insert_record('message_conversation_members', $member);
1381 return $conversation->id;
1385 * Checks if a user can create a contact request.
1387 * @param int $userid The id of the user who is creating the contact request
1388 * @param int $requesteduserid The id of the user being requested
1391 public static function can_create_contact(int $userid, int $requesteduserid) : bool {
1394 // If we can't message at all, then we can't create a contact.
1395 if (empty($CFG->messaging)) {
1399 // If we can message anyone on the site then we can create a contact.
1400 if ($CFG->messagingallusers) {
1404 // We need to check if they are in the same course.
1405 return enrol_sharing_course($userid, $requesteduserid);
1409 * Handles creating a contact request.
1411 * @param int $userid The id of the user who is creating the contact request
1412 * @param int $requesteduserid The id of the user being requested
1414 public static function create_contact_request(int $userid, int $requesteduserid) {
1417 $request = new \stdClass();
1418 $request->userid = $userid;
1419 $request->requesteduserid = $requesteduserid;
1420 $request->timecreated = time();
1422 $DB->insert_record('message_contact_requests', $request);
1424 // Send a notification.
1425 $userfrom = \core_user::get_user($userid);
1426 $userfromfullname = fullname($userfrom);
1427 $userto = \core_user::get_user($requesteduserid);
1428 $url = new \moodle_url('/message/pendingcontactrequests.php');
1430 $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
1431 $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);
1433 $message = new \core\message\message();
1434 $message->courseid = SITEID;
1435 $message->component = 'moodle';
1436 $message->name = 'messagecontactrequests';
1437 $message->notification = 1;
1438 $message->userfrom = $userfrom;
1439 $message->userto = $userto;
1440 $message->subject = $subject;
1441 $message->fullmessage = text_to_html($fullmessage);
1442 $message->fullmessageformat = FORMAT_HTML;
1443 $message->fullmessagehtml = $fullmessage;
1444 $message->smallmessage = '';
1445 $message->contexturl = $url->out(false);
1447 message_send($message);
1452 * Handles confirming a contact request.
1454 * @param int $userid The id of the user who created the contact request
1455 * @param int $requesteduserid The id of the user confirming the request
1457 public static function confirm_contact_request(int $userid, int $requesteduserid) {
1460 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1461 'requesteduserid' => $requesteduserid])) {
1462 self::add_contact($userid, $requesteduserid);
1464 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1469 * Handles declining a contact request.
1471 * @param int $userid The id of the user who created the contact request
1472 * @param int $requesteduserid The id of the user declining the request
1474 public static function decline_contact_request(int $userid, int $requesteduserid) {
1477 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1478 'requesteduserid' => $requesteduserid])) {
1479 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1484 * Handles returning the contact requests for a user.
1486 * This also includes the user data necessary to display information
1489 * It will not include blocked users.
1491 * @param int $userid
1492 * @return array The list of contact requests
1494 public static function get_contact_requests(int $userid) : array {
1497 // Used to search for contacts.
1498 $ufields = \user_picture::fields('u');
1500 $sql = "SELECT $ufields, mcr.id as contactrequestid
1502 JOIN {message_contact_requests} mcr
1503 ON u.id = mcr.userid
1504 LEFT JOIN {message_users_blocked} mub
1505 ON (mub.userid = ? AND mub.blockeduserid = u.id)
1506 WHERE mcr.requesteduserid = ?
1509 ORDER BY mcr.timecreated DESC";
1511 return $DB->get_records_sql($sql, [$userid, $userid]);
1515 * Handles adding a contact.
1517 * @param int $userid The id of the user who requested to be a contact
1518 * @param int $contactid The id of the contact
1520 public static function add_contact(int $userid, int $contactid) {
1523 $messagecontact = new \stdClass();
1524 $messagecontact->userid = $userid;
1525 $messagecontact->contactid = $contactid;
1526 $messagecontact->timecreated = time();
1527 $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
1530 'objectid' => $messagecontact->id,
1531 'userid' => $userid,
1532 'relateduserid' => $contactid,
1533 'context' => \context_user::instance($userid)
1535 $event = \core\event\message_contact_added::create($eventparams);
1536 $event->add_record_snapshot('message_contacts', $messagecontact);
1541 * Handles removing a contact.
1543 * @param int $userid The id of the user who is removing a user as a contact
1544 * @param int $contactid The id of the user to be removed as a contact
1546 public static function remove_contact(int $userid, int $contactid) {
1549 if ($contact = self::get_contact($userid, $contactid)) {
1550 $DB->delete_records('message_contacts', ['id' => $contact->id]);
1552 $event = \core\event\message_contact_removed::create(array(
1553 'objectid' => $contact->id,
1554 'userid' => $userid,
1555 'relateduserid' => $contactid,
1556 'context' => \context_user::instance($userid)
1558 $event->add_record_snapshot('message_contacts', $contact);
1564 * Handles blocking a user.
1566 * @param int $userid The id of the user who is blocking
1567 * @param int $usertoblockid The id of the user being blocked
1569 public static function block_user(int $userid, int $usertoblockid) {
1572 $blocked = new \stdClass();
1573 $blocked->userid = $userid;
1574 $blocked->blockeduserid = $usertoblockid;
1575 $blocked->timecreated = time();
1576 $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
1578 // Trigger event for blocking a contact.
1579 $event = \core\event\message_user_blocked::create(array(
1580 'objectid' => $blocked->id,
1581 'userid' => $userid,
1582 'relateduserid' => $usertoblockid,
1583 'context' => \context_user::instance($userid)
1585 $event->add_record_snapshot('message_users_blocked', $blocked);
1590 * Handles unblocking a user.
1592 * @param int $userid The id of the user who is unblocking
1593 * @param int $usertounblockid The id of the user being unblocked
1595 public static function unblock_user(int $userid, int $usertounblockid) {
1598 if ($blockeduser = $DB->get_record('message_users_blocked',
1599 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
1600 $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
1602 // Trigger event for unblocking a contact.
1603 $event = \core\event\message_user_unblocked::create(array(
1604 'objectid' => $blockeduser->id,
1605 'userid' => $userid,
1606 'relateduserid' => $usertounblockid,
1607 'context' => \context_user::instance($userid)
1609 $event->add_record_snapshot('message_users_blocked', $blockeduser);
1615 * Checks if users are already contacts.
1617 * @param int $userid The id of one of the users
1618 * @param int $contactid The id of the other user
1619 * @return bool Returns true if they are a contact, false otherwise
1621 public static function is_contact(int $userid, int $contactid) : bool {
1625 FROM {message_contacts} mc
1626 WHERE (mc.userid = ? AND mc.contactid = ?)
1627 OR (mc.userid = ? AND mc.contactid = ?)";
1628 return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
1632 * Returns the row in the database table message_contacts that represents the contact between two people.
1634 * @param int $userid The id of one of the users
1635 * @param int $contactid The id of the other user
1636 * @return mixed A fieldset object containing the record, false otherwise
1638 public static function get_contact(int $userid, int $contactid) {
1642 FROM {message_contacts} mc
1643 WHERE (mc.userid = ? AND mc.contactid = ?)
1644 OR (mc.userid = ? AND mc.contactid = ?)";
1645 return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
1649 * Checks if a user is already blocked.
1651 * @param int $userid
1652 * @param int $blockeduserid
1653 * @return bool Returns true if they are a blocked, false otherwise
1655 public static function is_blocked(int $userid, int $blockeduserid) : bool {
1658 return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
1662 * Checks if a contact request already exists between users.
1664 * @param int $userid The id of the user who is creating the contact request
1665 * @param int $requesteduserid The id of the user being requested
1666 * @return bool Returns true if a contact request exists, false otherwise
1668 public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
1672 FROM {message_contact_requests} mcr
1673 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
1674 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
1675 return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
1679 * Checks if a user is already in a conversation.
1681 * @param int $userid The id of the user we want to check if they are in a group
1682 * @param int $conversationid The id of the conversation
1683 * @return bool Returns true if a contact request exists, false otherwise
1685 public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
1688 return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
1689 'userid' => $userid]);