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 * Handles searching for messages in the message area.
52 * @param int $userid The user id doing the searching
53 * @param string $search The string the user is searching
54 * @param int $limitfrom
55 * @param int $limitnum
58 public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
61 // Get the user fields we want.
62 $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
63 $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
65 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto, m.subject, m.fullmessage, m.fullmessagehtml, m.fullmessageformat,
66 m.smallmessage, m.timecreated, 0 as isread, $ufields, mub.id as userfrom_blocked, $ufields2,
67 mub2.id as userto_blocked
70 ON u.id = m.useridfrom
71 INNER JOIN {message_conversations} mc
72 ON mc.id = m.conversationid
73 INNER JOIN {message_conversation_members} mcm
74 ON mcm.conversationid = m.conversationid
77 LEFT JOIN {message_users_blocked} mub
78 ON (mub.blockeduserid = u.id AND mub.userid = ?)
79 LEFT JOIN {message_users_blocked} mub2
80 ON (mub2.blockeduserid = u2.id AND mub2.userid = ?)
81 LEFT JOIN {message_user_actions} mua
82 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
83 WHERE (m.useridfrom = ? OR mcm.userid = ?)
84 AND m.useridfrom != mcm.userid
88 AND " . $DB->sql_like('smallmessage', '?', false) . "
89 ORDER BY timecreated DESC";
91 $params = array($userid, $userid, $userid, self::MESSAGE_ACTION_DELETED, $userid, $userid, '%' . $search . '%');
93 // Convert the messages into searchable contacts with their last message being the message that was searched.
94 $conversations = array();
95 if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
96 foreach ($messages as $message) {
97 $prefix = 'userfrom_';
98 if ($userid == $message->useridfrom) {
100 // If it from the user, then mark it as read, even if it wasn't by the receiver.
101 $message->isread = true;
103 $blockedcol = $prefix . 'blocked';
104 $message->blocked = $message->$blockedcol ? 1 : 0;
106 $message->messageid = $message->id;
107 $conversations[] = helper::create_contact($message, $prefix);
111 return $conversations;
115 * Handles searching for user in a particular course in the message area.
117 * @param int $userid The user id doing the searching
118 * @param int $courseid The id of the course we are searching in
119 * @param string $search The string the user is searching
120 * @param int $limitfrom
121 * @param int $limitnum
124 public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
127 // Get all the users in the course.
128 list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
129 $sql = "SELECT u.*, mub.id as isblocked
133 LEFT JOIN {message_users_blocked} mub
134 ON (mub.blockeduserid = u.id AND mub.userid = :userid)
135 WHERE u.deleted = 0";
136 // Add more conditions.
137 $fullname = $DB->sql_fullname();
138 $sql .= " AND u.id != :userid2
139 AND " . $DB->sql_like($fullname, ':search', false) . "
140 ORDER BY " . $DB->sql_fullname();
141 $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
143 // Convert all the user records into contacts.
145 if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
146 foreach ($users as $user) {
147 $user->blocked = $user->isblocked ? 1 : 0;
148 $contacts[] = helper::create_contact($user);
156 * Handles searching for user in the message area.
158 * @param int $userid The user id doing the searching
159 * @param string $search The string the user is searching
160 * @param int $limitnum
163 public static function search_users($userid, $search, $limitnum = 0) {
166 // Used to search for contacts.
167 $fullname = $DB->sql_fullname();
168 $ufields = \user_picture::fields('u', array('lastaccess'));
170 // Users not to include.
171 $excludeusers = array($userid, $CFG->siteguest);
172 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
174 // Ok, let's search for contacts first.
176 $sql = "SELECT $ufields, mub.id as isuserblocked
178 JOIN {message_contacts} mc
179 ON u.id = mc.contactid
180 LEFT JOIN {message_users_blocked} mub
181 ON (mub.userid = :userid2 AND mub.blockeduserid = u.id)
182 WHERE mc.userid = :userid
185 AND " . $DB->sql_like($fullname, ':search', false) . "
187 ORDER BY " . $DB->sql_fullname();
188 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'userid2' => $userid,
189 'search' => '%' . $search . '%') + $excludeparams, 0, $limitnum)) {
190 foreach ($users as $user) {
191 $user->blocked = $user->isuserblocked ? 1 : 0;
192 $contacts[] = helper::create_contact($user);
196 // Now, let's get the courses.
197 // Make sure to limit searches to enrolled courses.
198 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
200 // Really we want the user to be able to view the participants if they have the capability
201 // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
202 // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
203 // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
204 if ($arrcourses = \core_course_category::search_courses(array('search' => $search), array('limit' => $limitnum),
205 array('moodle/course:viewparticipants'))) {
206 foreach ($arrcourses as $course) {
207 if (isset($enrolledcourses[$course->id])) {
208 $data = new \stdClass();
209 $data->id = $course->id;
210 $data->shortname = $course->shortname;
211 $data->fullname = $course->fullname;
217 // Let's get those non-contacts. Toast them gears boi.
218 // Note - you can only block contacts, so these users will not be blocked, so no need to get that
219 // extra detail from the database.
220 $noncontacts = array();
221 $sql = "SELECT $ufields
225 AND " . $DB->sql_like($fullname, ':search', false) . "
227 AND u.id NOT IN (SELECT contactid
228 FROM {message_contacts}
229 WHERE userid = :userid)
230 ORDER BY " . $DB->sql_fullname();
231 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
233 foreach ($users as $user) {
234 $noncontacts[] = helper::create_contact($user);
238 return array($contacts, $courses, $noncontacts);
242 * Returns the contacts and their conversation to display in the contacts area.
245 * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
246 * to retrieve too much information in a single call will cause performance problems.
249 * This function has specifically been altered to break each of the data sets it
250 * requires into separate database calls. This is to avoid the performance problems
251 * observed when attempting to join large data sets (e.g. the message tables and
254 * While it is possible to gather the data in a single query, and it may even be
255 * more efficient with a correctly tuned database, we have opted to trade off some of
256 * the benefits of a single query in order to ensure this function will work on
257 * most databases with default tunings and with large data sets.
259 * @param int $userid The user id
260 * @param int $limitfrom
261 * @param int $limitnum
264 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20) {
267 // Get the last message from each conversation that the user belongs to.
268 $sql = "SELECT m.id, m.conversationid, m.useridfrom, mcm2.userid as useridto, m.smallmessage, m.timecreated
271 SELECT MAX(m.id) AS messageid
274 SELECT m.conversationid, MAX(m.timecreated) as maxtime
276 INNER JOIN {message_conversation_members} mcm
277 ON mcm.conversationid = m.conversationid
278 LEFT JOIN {message_user_actions} mua
279 ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
281 AND mcm.userid = :userid2
282 GROUP BY m.conversationid
284 ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
285 GROUP BY m.conversationid
287 ON lastmessage.messageid = m.id
288 INNER JOIN {message_conversation_members} mcm
289 ON mcm.conversationid = m.conversationid
290 INNER JOIN {message_conversation_members} mcm2
291 ON mcm2.conversationid = m.conversationid
292 WHERE mcm.userid = m.useridfrom
293 AND mcm.id != mcm2.id
294 ORDER BY m.timecreated DESC";
295 $messageset = $DB->get_recordset_sql($sql, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
296 'userid2' => $userid], $limitfrom, $limitnum);
299 foreach ($messageset as $message) {
300 $messages[$message->id] = $message;
302 $messageset->close();
304 // If there are no messages return early.
305 if (empty($messages)) {
309 // We need to pull out the list of other users that are part of each of these conversations. This
310 // needs to be done in a separate query to avoid doing a join on the messages tables and the user
311 // tables because on large sites these tables are massive which results in extremely slow
312 // performance (typically due to join buffer exhaustion).
313 $otheruserids = array_map(function($message) use ($userid) {
314 return ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
315 }, array_values($messages));
317 // Ok, let's get the other members in the conversations.
318 list($useridsql, $usersparams) = $DB->get_in_or_equal($otheruserids);
319 $userfields = \user_picture::fields('u', array('lastaccess'));
320 $userssql = "SELECT $userfields
324 $otherusers = $DB->get_records_sql($userssql, $usersparams);
326 // If there are no other users (user may have been deleted), then do not continue.
327 if (empty($otherusers)) {
331 $contactssql = "SELECT contactid
332 FROM {message_contacts}
334 AND contactid $useridsql";
335 $contacts = $DB->get_records_sql($contactssql, array_merge([$userid], $usersparams));
337 // Finally, let's get the unread messages count for this user so that we can add them
338 // to the conversation. Remember we need to ignore the messages the user sent.
339 $unreadcountssql = 'SELECT m.useridfrom, count(m.id) as count
341 INNER JOIN {message_conversations} mc
342 ON mc.id = m.conversationid
343 INNER JOIN {message_conversation_members} mcm
344 ON m.conversationid = mcm.conversationid
345 LEFT JOIN {message_user_actions} mua
346 ON (mua.messageid = m.id AND mua.userid = ? AND
347 (mua.action = ? OR mua.action = ?))
349 AND m.useridfrom != ?
351 GROUP BY useridfrom';
352 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
355 // Get rid of the table prefix.
356 $userfields = str_replace('u.', '', $userfields);
357 $userproperties = explode(',', $userfields);
358 $arrconversations = array();
359 foreach ($messages as $message) {
360 $conversation = new \stdClass();
361 $otheruserid = ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
362 $otheruser = isset($otherusers[$otheruserid]) ? $otherusers[$otheruserid] : null;
363 $contact = isset($contacts[$otheruserid]) ? $contacts[$otheruserid] : null;
365 // It's possible the other user was deleted, so, skip.
366 if (is_null($otheruser)) {
370 // Add the other user's information to the conversation, if we have one.
371 foreach ($userproperties as $prop) {
372 $conversation->$prop = ($otheruser) ? $otheruser->$prop : null;
375 // Add the contact's information, if we have one.
376 $conversation->blocked = ($contact) ? $contact->blocked : null;
378 // Add the message information.
379 $conversation->messageid = $message->id;
380 $conversation->smallmessage = $message->smallmessage;
381 $conversation->useridfrom = $message->useridfrom;
383 // Only consider it unread if $user has unread messages.
384 if (isset($unreadcounts[$otheruserid])) {
385 $conversation->isread = false;
386 $conversation->unreadcount = $unreadcounts[$otheruserid]->count;
388 $conversation->isread = true;
391 $arrconversations[$otheruserid] = helper::create_contact($conversation);
394 return $arrconversations;
398 * Returns the contacts to display in the contacts area.
400 * @param int $userid The user id
401 * @param int $limitfrom
402 * @param int $limitnum
405 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
410 FROM {message_contacts} mc
411 WHERE mc.userid = ? OR mc.contactid = ?
412 ORDER BY timecreated DESC";
413 if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
414 foreach ($contacts as $contact) {
415 if ($userid == $contact->userid) {
416 $contactids[] = $contact->contactid;
418 $contactids[] = $contact->userid;
423 if (!empty($contactids)) {
424 list($insql, $inparams) = $DB->get_in_or_equal($contactids);
426 $sql = "SELECT u.*, mub.id as isblocked
428 LEFT JOIN {message_users_blocked} mub
429 ON u.id = mub.blockeduserid
431 if ($contacts = $DB->get_records_sql($sql, $inparams)) {
433 foreach ($contacts as $contact) {
434 $contact->blocked = $contact->isblocked ? 1 : 0;
435 $arrcontacts[] = helper::create_contact($contact);
446 * Returns the an array of the users the given user is in a conversation
447 * with who are a contact and the number of unread messages.
449 * @param int $userid The user id
450 * @param int $limitfrom
451 * @param int $limitnum
454 public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
457 $userfields = \user_picture::fields('u', array('lastaccess'));
458 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
459 FROM {message_contacts} mc
461 ON (u.id = mc.contactid OR u.id = mc.userid)
462 LEFT JOIN {messages} m
463 ON ((m.useridfrom = mc.contactid OR m.useridfrom = mc.userid) AND m.useridfrom != ?)
464 LEFT JOIN {message_conversation_members} mcm
465 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
466 LEFT JOIN {message_user_actions} mua
467 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
468 LEFT JOIN {message_users_blocked} mub
469 ON (mub.userid = ? AND mub.blockeduserid = u.id)
472 AND (mc.userid = ? OR mc.contactid = ?)
475 GROUP BY $userfields";
477 return $DB->get_records_sql($unreadcountssql, [$userid, $userid, $userid, self::MESSAGE_ACTION_READ,
478 $userid, $userid, $userid, $userid], $limitfrom, $limitnum);
482 * Returns the an array of the users the given user is in a conversation
483 * with who are not a contact and the number of unread messages.
485 * @param int $userid The user id
486 * @param int $limitfrom
487 * @param int $limitnum
490 public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
493 $userfields = \user_picture::fields('u', array('lastaccess'));
494 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
496 INNER JOIN {messages} m
497 ON m.useridfrom = u.id
498 INNER JOIN {message_conversation_members} mcm
499 ON mcm.conversationid = m.conversationid
500 LEFT JOIN {message_user_actions} mua
501 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
502 LEFT JOIN {message_contacts} mc
503 ON (mc.userid = ? AND mc.contactid = u.id)
504 LEFT JOIN {message_users_blocked} mub
505 ON (mub.userid = ? AND mub.blockeduserid = u.id)
507 AND mcm.userid != m.useridfrom
512 GROUP BY $userfields";
514 return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
515 $limitfrom, $limitnum);
519 * Returns the messages to display in the message area.
521 * @param int $userid the current user
522 * @param int $otheruserid the other user
523 * @param int $limitfrom
524 * @param int $limitnum
525 * @param string $sort
526 * @param int $timefrom the time from the message being sent
527 * @param int $timeto the time up until the message being sent
530 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
531 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
533 if (!empty($timefrom)) {
534 // Check the cache to see if we even need to do a DB query.
535 $cache = \cache::make('core', 'message_time_last_message_between_users');
536 $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
537 $lastcreated = $cache->get($key);
539 // The last known message time is earlier than the one being requested so we can
540 // just return an empty result set rather than having to query the DB.
541 if ($lastcreated && $lastcreated < $timefrom) {
546 $arrmessages = array();
547 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
548 $sort, $timefrom, $timeto)) {
550 $arrmessages = helper::create_messages($userid, $messages);
557 * Returns the most recent message between two users.
559 * @param int $userid the current user
560 * @param int $otheruserid the other user
561 * @return \stdClass|null
563 public static function get_most_recent_message($userid, $otheruserid) {
564 // We want two messages here so we get an accurate 'blocktime' value.
565 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
566 // Swap the order so we now have them in historical order.
567 $messages = array_reverse($messages);
568 $arrmessages = helper::create_messages($userid, $messages);
569 return array_pop($arrmessages);
576 * Returns the profile information for a contact for a user.
578 * @param int $userid The user id
579 * @param int $otheruserid The id of the user whose profile we want to view.
582 public static function get_profile($userid, $otheruserid) {
585 require_once($CFG->dirroot . '/user/lib.php');
587 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
589 // Create the data we are going to pass to the renderable.
590 $data = new \stdClass();
591 $data->userid = $otheruserid;
592 $data->fullname = fullname($user);
596 $data->isonline = null;
597 // Get the user picture data - messaging has always shown these to the user.
598 $userpicture = new \user_picture($user);
599 $userpicture->size = 1; // Size f1.
600 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
601 $userpicture->size = 0; // Size f2.
602 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
604 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
606 if (isset($userfields['city'])) {
607 $data->city = $userfields['city'];
609 if (isset($userfields['country'])) {
610 $data->country = $userfields['country'];
612 if (isset($userfields['email'])) {
613 $data->email = $userfields['email'];
615 if (isset($userfields['lastaccess'])) {
616 $data->isonline = helper::is_online($userfields['lastaccess']);
620 $data->isblocked = self::is_blocked($userid, $otheruserid);
621 $data->iscontact = self::is_contact($userid, $otheruserid);
627 * Checks if a user can delete messages they have either received or sent.
629 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
630 * but will still seem as if it was by the user)
631 * @return bool Returns true if a user can delete the conversation, false otherwise.
633 public static function can_delete_conversation($userid) {
636 $systemcontext = \context_system::instance();
638 // Let's check if the user is allowed to delete this conversation.
639 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
640 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
641 $USER->id == $userid))) {
649 * Deletes a conversation.
651 * This function does not verify any permissions.
653 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
654 * but will still seem as if it was by the user)
655 * @param int $otheruserid The id of the other user in the conversation
658 public static function delete_conversation($userid, $otheruserid) {
661 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
663 // If there is no conversation, there is nothing to do.
664 if (!$conversationid) {
668 // Get all messages belonging to this conversation that have not already been deleted by this user.
671 INNER JOIN {message_conversations} mc
672 ON m.conversationid = mc.id
673 LEFT JOIN {message_user_actions} mua
674 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
677 ORDER BY m.timecreated ASC";
678 $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
680 // Ok, mark these as deleted.
681 foreach ($messages as $message) {
682 $mua = new \stdClass();
683 $mua->userid = $userid;
684 $mua->messageid = $message->id;
685 $mua->action = self::MESSAGE_ACTION_DELETED;
686 $mua->timecreated = time();
687 $mua->id = $DB->insert_record('message_user_actions', $mua);
689 if ($message->useridfrom == $userid) {
690 $useridto = $otheruserid;
694 \core\event\message_deleted::create_from_ids($message->useridfrom, $useridto,
695 $USER->id, $message->id, $mua->id)->trigger();
702 * Returns the count of unread conversations (collection of messages from a single user) for
705 * @param \stdClass $user the user who's conversations should be counted
706 * @return int the count of the user's unread conversations
708 public static function count_unread_conversations($user = null) {
715 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
717 INNER JOIN {message_conversations} mc
718 ON m.conversationid = mc.id
719 INNER JOIN {message_conversation_members} mcm
720 ON mc.id = mcm.conversationid
721 LEFT JOIN {message_user_actions} mua
722 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
724 AND mcm.userid != m.useridfrom
727 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
731 * Marks all messages being sent to a user in a particular conversation.
733 * If $conversationdid is null then it marks all messages as read sent to $userid.
736 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
738 public static function mark_all_messages_as_read($userid, $conversationid = null) {
741 $messagesql = "SELECT m.*
743 INNER JOIN {message_conversations} mc
744 ON mc.id = m.conversationid
745 INNER JOIN {message_conversation_members} mcm
746 ON mcm.conversationid = mc.id
747 LEFT JOIN {message_user_actions} mua
748 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
751 AND m.useridfrom != ?";
753 $messageparams[] = $userid;
754 $messageparams[] = self::MESSAGE_ACTION_READ;
755 $messageparams[] = $userid;
756 $messageparams[] = $userid;
757 if (!is_null($conversationid)) {
758 $messagesql .= " AND mc.id = ?";
759 $messageparams[] = $conversationid;
762 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
763 foreach ($messages as $message) {
764 self::mark_message_as_read($userid, $message);
770 * Marks all notifications being sent from one user to another user as read.
772 * If the from user is null then it marks all notifications as read sent to the to user.
774 * @param int $touserid the id of the message recipient
775 * @param int|null $fromuserid the id of the message sender, null if all messages
778 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
781 $notificationsql = "SELECT n.*
782 FROM {notifications} n
784 AND timeread is NULL";
785 $notificationsparams = [$touserid];
786 if (!empty($fromuserid)) {
787 $notificationsql .= " AND useridfrom = ?";
788 $notificationsparams[] = $fromuserid;
791 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
792 foreach ($notifications as $notification) {
793 self::mark_notification_as_read($notification);
795 $notifications->close();
799 * Marks ALL messages being sent from $fromuserid to $touserid as read.
801 * Can be filtered by type.
803 * @deprecated since 3.5
804 * @param int $touserid the id of the message recipient
805 * @param int $fromuserid the id of the message sender
806 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
809 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
810 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
811 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
814 $type = strtolower($type);
816 $conversationid = null;
817 $ignoremessages = false;
818 if (!empty($fromuserid)) {
819 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
820 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
821 $ignoremessages = true;
826 if ($type == MESSAGE_TYPE_NOTIFICATION) {
827 self::mark_all_notifications_as_read($touserid, $fromuserid);
828 } else if ($type == MESSAGE_TYPE_MESSAGE) {
829 if (!$ignoremessages) {
830 self::mark_all_messages_as_read($touserid, $conversationid);
833 } else { // We want both.
834 self::mark_all_notifications_as_read($touserid, $fromuserid);
835 if (!$ignoremessages) {
836 self::mark_all_messages_as_read($touserid, $conversationid);
842 * Returns message preferences.
844 * @param array $processors
845 * @param array $providers
846 * @param \stdClass $user
850 public static function get_all_message_preferences($processors, $providers, $user) {
851 $preferences = helper::get_providers_preferences($providers, $user->id);
852 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
854 // For every processors put its options on the form (need to get function from processor's lib.php).
855 foreach ($processors as $processor) {
856 $processor->object->load_data($preferences, $user->id);
859 // Load general messaging preferences.
860 $preferences->blocknoncontacts = get_user_preferences('message_blocknoncontacts', '', $user->id);
861 $preferences->mailformat = $user->mailformat;
862 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
868 * Count the number of users blocked by a user.
870 * @param \stdClass $user The user object
871 * @return int the number of blocked users
873 public static function count_blocked_users($user = null) {
880 $sql = "SELECT count(mub.id)
881 FROM {message_users_blocked} mub
882 WHERE mub.userid = :userid";
883 return $DB->count_records_sql($sql, array('userid' => $user->id));
887 * Determines if a user is permitted to send another user a private message.
888 * If no sender is provided then it defaults to the logged in user.
890 * @param \stdClass $recipient The user object.
891 * @param \stdClass|null $sender The user object.
892 * @return bool true if user is permitted, false otherwise.
894 public static function can_post_message($recipient, $sender = null) {
897 if (is_null($sender)) {
898 // The message is from the logged in user, unless otherwise specified.
902 if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
906 // The recipient blocks messages from non-contacts and the
907 // sender isn't a contact.
908 if (self::is_user_non_contact_blocked($recipient, $sender)) {
913 if ($sender !== null && isset($sender->id)) {
914 $senderid = $sender->id;
917 $systemcontext = \context_system::instance();
918 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
922 // The recipient has specifically blocked this sender.
923 if (self::is_blocked($recipient->id, $senderid)) {
931 * Checks if the recipient is allowing messages from users that aren't a
932 * contact. If not then it checks to make sure the sender is in the
933 * recipient's contacts.
935 * @param \stdClass $recipient The user object.
936 * @param \stdClass|null $sender The user object.
937 * @return bool true if $sender is blocked, false otherwise.
939 public static function is_user_non_contact_blocked($recipient, $sender = null) {
942 if (is_null($sender)) {
943 // The message is from the logged in user, unless otherwise specified.
947 $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
948 if (!empty($blockednoncontacts)) {
949 // Confirm the sender is a contact of the recipient.
950 if (self::is_contact($sender->id, $recipient->id)) {
951 // All good, the recipient is a contact of the sender.
954 // Oh no, the recipient is not a contact. Looks like we can't send the message.
963 * Checks if the recipient has specifically blocked the sending user.
965 * Note: This function will always return false if the sender has the
966 * readallmessages capability at the system context level.
968 * @deprecated since 3.6
969 * @param int $recipientid User ID of the recipient.
970 * @param int $senderid User ID of the sender.
971 * @return bool true if $sender is blocked, false otherwise.
973 public static function is_user_blocked($recipientid, $senderid = null) {
974 debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
979 if (is_null($senderid)) {
980 // The message is from the logged in user, unless otherwise specified.
981 $senderid = $USER->id;
984 $systemcontext = \context_system::instance();
985 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
989 if (self::is_blocked($recipientid, $senderid)) {
997 * Get specified message processor, validate corresponding plugin existence and
998 * system configuration.
1000 * @param string $name Name of the processor.
1001 * @param bool $ready only return ready-to-use processors.
1002 * @return mixed $processor if processor present else empty array.
1005 public static function get_message_processor($name, $ready = false) {
1008 $processor = $DB->get_record('message_processors', array('name' => $name));
1009 if (empty($processor)) {
1010 // Processor not found, return.
1014 $processor = self::get_processed_processor_object($processor);
1016 if ($processor->enabled && $processor->configured) {
1027 * Returns weather a given processor is enabled or not.
1028 * Note:- This doesn't check if the processor is configured or not.
1030 * @param string $name Name of the processor
1033 public static function is_processor_enabled($name) {
1035 $cache = \cache::make('core', 'message_processors_enabled');
1036 $status = $cache->get($name);
1038 if ($status === false) {
1039 $processor = self::get_message_processor($name);
1040 if (!empty($processor)) {
1041 $cache->set($name, $processor->enabled);
1042 return $processor->enabled;
1052 * Set status of a processor.
1054 * @param \stdClass $processor processor record.
1055 * @param 0|1 $enabled 0 or 1 to set the processor status.
1059 public static function update_processor_status($processor, $enabled) {
1061 $cache = \cache::make('core', 'message_processors_enabled');
1062 $cache->delete($processor->name);
1063 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1067 * Given a processor object, loads information about it's settings and configurations.
1068 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1069 * or @see \get_message_processors()
1071 * @param \stdClass $processor processor object
1072 * @return \stdClass processed processor object
1075 public static function get_processed_processor_object(\stdClass $processor) {
1078 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1079 if (is_readable($processorfile)) {
1080 include_once($processorfile);
1081 $processclass = 'message_output_' . $processor->name;
1082 if (class_exists($processclass)) {
1083 $pclass = new $processclass();
1084 $processor->object = $pclass;
1085 $processor->configured = 0;
1086 if ($pclass->is_system_configured()) {
1087 $processor->configured = 1;
1089 $processor->hassettings = 0;
1090 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1091 $processor->hassettings = 1;
1093 $processor->available = 1;
1095 print_error('errorcallingprocessor', 'message');
1098 $processor->available = 0;
1104 * Retrieve users blocked by $user1
1106 * @param int $userid The user id of the user whos blocked users we are returning
1107 * @return array the users blocked
1109 public static function get_blocked_users($userid) {
1112 $userfields = \user_picture::fields('u', array('lastaccess'));
1113 $blockeduserssql = "SELECT $userfields
1114 FROM {message_users_blocked} mub
1116 ON u.id = mub.blockeduserid
1119 GROUP BY $userfields
1120 ORDER BY u.firstname ASC";
1121 return $DB->get_records_sql($blockeduserssql, [$userid]);
1125 * Mark a single message as read.
1127 * @param int $userid The user id who marked the message as read
1128 * @param \stdClass $message The message
1129 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1131 public static function mark_message_as_read($userid, $message, $timeread = null) {
1134 if (is_null($timeread)) {
1138 $mua = new \stdClass();
1139 $mua->userid = $userid;
1140 $mua->messageid = $message->id;
1141 $mua->action = self::MESSAGE_ACTION_READ;
1142 $mua->timecreated = $timeread;
1143 $mua->id = $DB->insert_record('message_user_actions', $mua);
1145 // Get the context for the user who received the message.
1146 $context = \context_user::instance($userid, IGNORE_MISSING);
1147 // If the user no longer exists the context value will be false, in this case use the system context.
1148 if ($context === false) {
1149 $context = \context_system::instance();
1152 // Trigger event for reading a message.
1153 $event = \core\event\message_viewed::create(array(
1154 'objectid' => $mua->id,
1155 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1156 'context' => $context,
1157 'relateduserid' => $message->useridfrom,
1159 'messageid' => $message->id
1166 * Mark a single notification as read.
1168 * @param \stdClass $notification The notification
1169 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1171 public static function mark_notification_as_read($notification, $timeread = null) {
1174 if (is_null($timeread)) {
1178 if (is_null($notification->timeread)) {
1179 $updatenotification = new \stdClass();
1180 $updatenotification->id = $notification->id;
1181 $updatenotification->timeread = $timeread;
1183 $DB->update_record('notifications', $updatenotification);
1185 // Trigger event for reading a notification.
1186 \core\event\notification_viewed::create_from_ids(
1187 $notification->useridfrom,
1188 $notification->useridto,
1195 * Checks if a user can delete a message.
1197 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1198 * but will still seem as if it was by the user)
1199 * @param int $messageid The message id
1200 * @return bool Returns true if a user can delete the message, false otherwise.
1202 public static function can_delete_message($userid, $messageid) {
1205 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1207 INNER JOIN {message_conversations} mc
1208 ON m.conversationid = mc.id
1209 INNER JOIN {message_conversation_members} mcm
1210 ON mcm.conversationid = mc.id
1211 WHERE mcm.userid != m.useridfrom
1213 $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1215 if ($message->useridfrom == $userid) {
1216 $userdeleting = 'useridfrom';
1217 } else if ($message->useridto == $userid) {
1218 $userdeleting = 'useridto';
1223 $systemcontext = \context_system::instance();
1225 // Let's check if the user is allowed to delete this message.
1226 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
1227 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1228 $USER->id == $message->$userdeleting))) {
1236 * Deletes a message.
1238 * This function does not verify any permissions.
1240 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1241 * but will still seem as if it was by the user)
1242 * @param int $messageid The message id
1245 public static function delete_message($userid, $messageid) {
1248 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1250 INNER JOIN {message_conversations} mc
1251 ON m.conversationid = mc.id
1252 INNER JOIN {message_conversation_members} mcm
1253 ON mcm.conversationid = mc.id
1254 WHERE mcm.userid != m.useridfrom
1256 $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1258 // Check if the user has already deleted this message.
1259 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1260 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1261 $mua = new \stdClass();
1262 $mua->userid = $userid;
1263 $mua->messageid = $messageid;
1264 $mua->action = self::MESSAGE_ACTION_DELETED;
1265 $mua->timecreated = time();
1266 $mua->id = $DB->insert_record('message_user_actions', $mua);
1268 // Trigger event for deleting a message.
1269 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1270 $userid, $message->id, $mua->id)->trigger();
1279 * Returns the conversation between two users.
1281 * @param array $userids
1282 * @return int|bool The id of the conversation, false if not found
1284 public static function get_conversation_between_users(array $userids) {
1287 $hash = helper::get_conversation_hash($userids);
1289 if ($conversation = $DB->get_record('message_conversations', ['convhash' => $hash])) {
1290 return $conversation->id;
1297 * Creates a conversation between two users.
1299 * @param array $userids
1300 * @return int The id of the conversation
1302 public static function create_conversation_between_users(array $userids) {
1305 $conversation = new \stdClass();
1306 $conversation->convhash = helper::get_conversation_hash($userids);
1307 $conversation->timecreated = time();
1308 $conversation->id = $DB->insert_record('message_conversations', $conversation);
1310 // Add members to this conversation.
1311 foreach ($userids as $userid) {
1312 $member = new \stdClass();
1313 $member->conversationid = $conversation->id;
1314 $member->userid = $userid;
1315 $member->timecreated = time();
1316 $DB->insert_record('message_conversation_members', $member);
1319 return $conversation->id;
1323 * Checks if a user can create a contact request.
1325 * @param int $userid The id of the user who is creating the contact request
1326 * @param int $requesteduserid The id of the user being requested
1329 public static function can_create_contact(int $userid, int $requesteduserid) : bool {
1332 // If we can't message at all, then we can't create a contact.
1333 if (empty($CFG->messaging)) {
1337 // If we can message anyone on the site then we can create a contact.
1338 if ($CFG->messagingallusers) {
1342 // We need to check if they are in the same course.
1343 return enrol_sharing_course($userid, $requesteduserid);
1347 * Handles creating a contact request.
1349 * @param int $userid The id of the user who is creating the contact request
1350 * @param int $requesteduserid The id of the user being requested
1352 public static function create_contact_request(int $userid, int $requesteduserid) {
1355 $request = new \stdClass();
1356 $request->userid = $userid;
1357 $request->requesteduserid = $requesteduserid;
1358 $request->timecreated = time();
1360 $DB->insert_record('message_contact_requests', $request);
1362 // Send a notification.
1363 $userfrom = \core_user::get_user($userid);
1364 $userfromfullname = fullname($userfrom);
1365 $userto = \core_user::get_user($requesteduserid);
1366 $url = new \moodle_url('/message/pendingcontactrequests.php');
1368 $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
1369 $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);
1371 $message = new \core\message\message();
1372 $message->courseid = SITEID;
1373 $message->component = 'moodle';
1374 $message->name = 'messagecontactrequests';
1375 $message->notification = 1;
1376 $message->userfrom = $userfrom;
1377 $message->userto = $userto;
1378 $message->subject = $subject;
1379 $message->fullmessage = text_to_html($fullmessage);
1380 $message->fullmessageformat = FORMAT_HTML;
1381 $message->fullmessagehtml = $fullmessage;
1382 $message->smallmessage = '';
1383 $message->contexturl = $url->out(false);
1385 message_send($message);
1390 * Handles confirming a contact request.
1392 * @param int $userid The id of the user who created the contact request
1393 * @param int $requesteduserid The id of the user confirming the request
1395 public static function confirm_contact_request(int $userid, int $requesteduserid) {
1398 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1399 'requesteduserid' => $requesteduserid])) {
1400 self::add_contact($userid, $requesteduserid);
1402 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1407 * Handles declining a contact request.
1409 * @param int $userid The id of the user who created the contact request
1410 * @param int $requesteduserid The id of the user declining the request
1412 public static function decline_contact_request(int $userid, int $requesteduserid) {
1415 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1416 'requesteduserid' => $requesteduserid])) {
1417 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1422 * Handles returning the contact requests for a user.
1424 * This also includes the user data necessary to display information
1427 * It will not include blocked users.
1429 * @param int $userid
1430 * @return array The list of contact requests
1432 public static function get_contact_requests(int $userid) : array {
1435 // Used to search for contacts.
1436 $ufields = \user_picture::fields('u');
1438 $sql = "SELECT $ufields, mcr.id as contactrequestid
1440 JOIN {message_contact_requests} mcr
1441 ON u.id = mcr.userid
1442 LEFT JOIN {message_users_blocked} mub
1443 ON (mub.userid = ? AND mub.blockeduserid = u.id)
1444 WHERE mcr.requesteduserid = ?
1447 ORDER BY mcr.timecreated DESC";
1449 return $DB->get_records_sql($sql, [$userid, $userid]);
1453 * Handles adding a contact.
1455 * @param int $userid The id of the user who requested to be a contact
1456 * @param int $contactid The id of the contact
1458 public static function add_contact(int $userid, int $contactid) {
1461 $messagecontact = new \stdClass();
1462 $messagecontact->userid = $userid;
1463 $messagecontact->contactid = $contactid;
1464 $messagecontact->timecreated = time();
1465 $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
1468 'objectid' => $messagecontact->id,
1469 'userid' => $userid,
1470 'relateduserid' => $contactid,
1471 'context' => \context_user::instance($userid)
1473 $event = \core\event\message_contact_added::create($eventparams);
1474 $event->add_record_snapshot('message_contacts', $messagecontact);
1479 * Handles removing a contact.
1481 * @param int $userid The id of the user who is removing a user as a contact
1482 * @param int $contactid The id of the user to be removed as a contact
1484 public static function remove_contact(int $userid, int $contactid) {
1487 if ($contact = self::get_contact($userid, $contactid)) {
1488 $DB->delete_records('message_contacts', ['id' => $contact->id]);
1490 $event = \core\event\message_contact_removed::create(array(
1491 'objectid' => $contact->id,
1492 'userid' => $userid,
1493 'relateduserid' => $contactid,
1494 'context' => \context_user::instance($userid)
1496 $event->add_record_snapshot('message_contacts', $contact);
1502 * Handles blocking a user.
1504 * @param int $userid The id of the user who is blocking
1505 * @param int $usertoblockid The id of the user being blocked
1507 public static function block_user(int $userid, int $usertoblockid) {
1510 $blocked = new \stdClass();
1511 $blocked->userid = $userid;
1512 $blocked->blockeduserid = $usertoblockid;
1513 $blocked->timecreated = time();
1514 $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
1516 // Trigger event for blocking a contact.
1517 $event = \core\event\message_user_blocked::create(array(
1518 'objectid' => $blocked->id,
1519 'userid' => $userid,
1520 'relateduserid' => $usertoblockid,
1521 'context' => \context_user::instance($userid)
1523 $event->add_record_snapshot('message_users_blocked', $blocked);
1528 * Handles unblocking a user.
1530 * @param int $userid The id of the user who is unblocking
1531 * @param int $usertounblockid The id of the user being unblocked
1533 public static function unblock_user(int $userid, int $usertounblockid) {
1536 if ($blockeduser = $DB->get_record('message_users_blocked',
1537 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
1538 $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
1540 // Trigger event for unblocking a contact.
1541 $event = \core\event\message_user_unblocked::create(array(
1542 'objectid' => $blockeduser->id,
1543 'userid' => $userid,
1544 'relateduserid' => $usertounblockid,
1545 'context' => \context_user::instance($userid)
1547 $event->add_record_snapshot('message_users_blocked', $blockeduser);
1553 * Checks if users are already contacts.
1555 * @param int $userid The id of one of the users
1556 * @param int $contactid The id of the other user
1557 * @return bool Returns true if they are a contact, false otherwise
1559 public static function is_contact(int $userid, int $contactid) : bool {
1563 FROM {message_contacts} mc
1564 WHERE (mc.userid = ? AND mc.contactid = ?)
1565 OR (mc.userid = ? AND mc.contactid = ?)";
1566 return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
1570 * Returns the row in the database table message_contacts that represents the contact between two people.
1572 * @param int $userid The id of one of the users
1573 * @param int $contactid The id of the other user
1574 * @return mixed A fieldset object containing the record, false otherwise
1576 public static function get_contact(int $userid, int $contactid) {
1580 FROM {message_contacts} mc
1581 WHERE (mc.userid = ? AND mc.contactid = ?)
1582 OR (mc.userid = ? AND mc.contactid = ?)";
1583 return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
1587 * Checks if a user is already blocked.
1589 * @param int $userid
1590 * @param int $blockeduserid
1591 * @return bool Returns true if they are a blocked, false otherwise
1593 public static function is_blocked(int $userid, int $blockeduserid) : bool {
1596 return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
1600 * Checks if a contact request already exists between users.
1602 * @param int $userid The id of the user who is creating the contact request
1603 * @param int $requesteduserid The id of the user being requested
1604 * @return bool Returns true if a contact request exists, false otherwise
1606 public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
1610 FROM {message_contact_requests} mcr
1611 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
1612 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
1613 return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);