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, mcont.blocked as userfrom_blocked, $ufields2,
67 mcont2.blocked 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_contacts} mcont
78 ON (mcont.contactid = u.id AND mcont.userid = ?)
79 LEFT JOIN {message_contacts} mcont2
80 ON (mcont2.contactid = u2.id AND mcont2.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;
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.*, mc.blocked
133 LEFT JOIN {message_contacts} mc
134 ON (mc.contactid = u.id AND mc.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 $contacts[] = helper::create_contact($user);
155 * Handles searching for user in the message area.
157 * @param int $userid The user id doing the searching
158 * @param string $search The string the user is searching
159 * @param int $limitnum
162 public static function search_users($userid, $search, $limitnum = 0) {
165 require_once($CFG->dirroot . '/lib/coursecatlib.php');
167 // Used to search for contacts.
168 $fullname = $DB->sql_fullname();
169 $ufields = \user_picture::fields('u', array('lastaccess'));
171 // Users not to include.
172 $excludeusers = array($userid, $CFG->siteguest);
173 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
175 // Ok, let's search for contacts first.
177 $sql = "SELECT $ufields, mc.blocked
179 JOIN {message_contacts} mc
180 ON u.id = mc.contactid
181 WHERE mc.userid = :userid
184 AND " . $DB->sql_like($fullname, ':search', false) . "
186 ORDER BY " . $DB->sql_fullname();
187 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
189 foreach ($users as $user) {
190 $contacts[] = helper::create_contact($user);
194 // Now, let's get the courses.
195 // Make sure to limit searches to enrolled courses.
196 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
198 // Really we want the user to be able to view the participants if they have the capability
199 // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
200 // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
201 // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
202 if ($arrcourses = \coursecat::search_courses(array('search' => $search), array('limit' => $limitnum),
203 array('moodle/course:viewparticipants'))) {
204 foreach ($arrcourses as $course) {
205 if (isset($enrolledcourses[$course->id])) {
206 $data = new \stdClass();
207 $data->id = $course->id;
208 $data->shortname = $course->shortname;
209 $data->fullname = $course->fullname;
215 // Let's get those non-contacts. Toast them gears boi.
216 // Note - you can only block contacts, so these users will not be blocked, so no need to get that
217 // extra detail from the database.
218 $noncontacts = array();
219 $sql = "SELECT $ufields
223 AND " . $DB->sql_like($fullname, ':search', false) . "
225 AND u.id NOT IN (SELECT contactid
226 FROM {message_contacts}
227 WHERE userid = :userid)
228 ORDER BY " . $DB->sql_fullname();
229 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
231 foreach ($users as $user) {
232 $noncontacts[] = helper::create_contact($user);
236 return array($contacts, $courses, $noncontacts);
240 * Returns the contacts and their conversation to display in the contacts area.
243 * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
244 * to retrieve too much information in a single call will cause performance problems.
247 * This function has specifically been altered to break each of the data sets it
248 * requires into separate database calls. This is to avoid the performance problems
249 * observed when attempting to join large data sets (e.g. the message tables and
252 * While it is possible to gather the data in a single query, and it may even be
253 * more efficient with a correctly tuned database, we have opted to trade off some of
254 * the benefits of a single query in order to ensure this function will work on
255 * most databases with default tunings and with large data sets.
257 * @param int $userid The user id
258 * @param int $limitfrom
259 * @param int $limitnum
262 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20) {
265 // Get the last message from each conversation that the user belongs to.
266 $sql = "SELECT m.id, m.conversationid, m.useridfrom, mcm2.userid as useridto, m.smallmessage, m.timecreated
269 SELECT MAX(m.id) AS messageid
272 SELECT m.conversationid, MAX(m.timecreated) as maxtime
274 INNER JOIN {message_conversation_members} mcm
275 ON mcm.conversationid = m.conversationid
276 LEFT JOIN {message_user_actions} mua
277 ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
279 AND mcm.userid = :userid2
280 GROUP BY m.conversationid
282 ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
283 GROUP BY m.conversationid
285 ON lastmessage.messageid = m.id
286 INNER JOIN {message_conversation_members} mcm
287 ON mcm.conversationid = m.conversationid
288 INNER JOIN {message_conversation_members} mcm2
289 ON mcm2.conversationid = m.conversationid
290 WHERE mcm.userid = m.useridfrom
291 AND mcm.id != mcm2.id
292 ORDER BY m.timecreated DESC";
293 $messageset = $DB->get_recordset_sql($sql, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
294 'userid2' => $userid], $limitfrom, $limitnum);
297 foreach ($messageset as $message) {
298 $messages[$message->id] = $message;
300 $messageset->close();
302 // If there are no messages return early.
303 if (empty($messages)) {
307 // We need to pull out the list of other users that are part of each of these conversations. This
308 // needs to be done in a separate query to avoid doing a join on the messages tables and the user
309 // tables because on large sites these tables are massive which results in extremely slow
310 // performance (typically due to join buffer exhaustion).
311 $otheruserids = array_map(function($message) use ($userid) {
312 return ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
313 }, array_values($messages));
315 // Ok, let's get the other members in the conversations.
316 list($useridsql, $usersparams) = $DB->get_in_or_equal($otheruserids);
317 $userfields = \user_picture::fields('u', array('lastaccess'));
318 $userssql = "SELECT $userfields
322 $otherusers = $DB->get_records_sql($userssql, $usersparams);
324 // If there are no other users (user may have been deleted), then do not continue.
325 if (empty($otherusers)) {
329 $contactssql = "SELECT contactid, blocked
330 FROM {message_contacts}
332 AND contactid $useridsql";
333 $contacts = $DB->get_records_sql($contactssql, array_merge([$userid], $usersparams));
335 // Finally, let's get the unread messages count for this user so that we can add them
336 // to the conversation. Remember we need to ignore the messages the user sent.
337 $unreadcountssql = 'SELECT m.useridfrom, count(m.id) as count
339 INNER JOIN {message_conversations} mc
340 ON mc.id = m.conversationid
341 INNER JOIN {message_conversation_members} mcm
342 ON m.conversationid = mcm.conversationid
343 LEFT JOIN {message_user_actions} mua
344 ON (mua.messageid = m.id AND mua.userid = ? AND
345 (mua.action = ? OR mua.action = ?))
347 AND m.useridfrom != ?
349 GROUP BY useridfrom';
350 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
353 // Get rid of the table prefix.
354 $userfields = str_replace('u.', '', $userfields);
355 $userproperties = explode(',', $userfields);
356 $arrconversations = array();
357 foreach ($messages as $message) {
358 $conversation = new \stdClass();
359 $otheruserid = ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
360 $otheruser = isset($otherusers[$otheruserid]) ? $otherusers[$otheruserid] : null;
361 $contact = isset($contacts[$otheruserid]) ? $contacts[$otheruserid] : null;
363 // It's possible the other user was deleted, so, skip.
364 if (is_null($otheruser)) {
368 // Add the other user's information to the conversation, if we have one.
369 foreach ($userproperties as $prop) {
370 $conversation->$prop = ($otheruser) ? $otheruser->$prop : null;
373 // Add the contact's information, if we have one.
374 $conversation->blocked = ($contact) ? $contact->blocked : null;
376 // Add the message information.
377 $conversation->messageid = $message->id;
378 $conversation->smallmessage = $message->smallmessage;
379 $conversation->useridfrom = $message->useridfrom;
381 // Only consider it unread if $user has unread messages.
382 if (isset($unreadcounts[$otheruserid])) {
383 $conversation->isread = false;
384 $conversation->unreadcount = $unreadcounts[$otheruserid]->count;
386 $conversation->isread = true;
389 $arrconversations[$otheruserid] = helper::create_contact($conversation);
392 return $arrconversations;
396 * Returns the contacts to display in the contacts area.
398 * @param int $userid The user id
399 * @param int $limitfrom
400 * @param int $limitnum
403 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
406 $arrcontacts = array();
407 $sql = "SELECT u.*, mc.blocked
408 FROM {message_contacts} mc
410 ON mc.contactid = u.id
411 WHERE mc.userid = :userid
413 ORDER BY " . $DB->sql_fullname();
414 if ($contacts = $DB->get_records_sql($sql, array('userid' => $userid), $limitfrom, $limitnum)) {
415 foreach ($contacts as $contact) {
416 $arrcontacts[] = helper::create_contact($contact);
424 * Returns the an array of the users the given user is in a conversation
425 * with who are a contact and the number of unread messages.
427 * @param int $userid The user id
428 * @param int $limitfrom
429 * @param int $limitnum
432 public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
435 $userfields = \user_picture::fields('u', array('lastaccess'));
436 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
437 FROM {message_contacts} mc
439 ON u.id = mc.contactid
440 LEFT JOIN {messages} m
441 ON m.useridfrom = mc.contactid
442 LEFT JOIN {message_conversation_members} mcm
443 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
444 LEFT JOIN {message_user_actions} mua
445 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
450 GROUP BY $userfields";
452 return $DB->get_records_sql($unreadcountssql, [$userid, $userid, self::MESSAGE_ACTION_READ,
453 $userid, $userid], $limitfrom, $limitnum);
457 * Returns the an array of the users the given user is in a conversation
458 * with who are not a contact and the number of unread messages.
460 * @param int $userid The user id
461 * @param int $limitfrom
462 * @param int $limitnum
465 public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
468 $userfields = \user_picture::fields('u', array('lastaccess'));
469 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
471 INNER JOIN {messages} m
472 ON m.useridfrom = u.id
473 INNER JOIN {message_conversation_members} mcm
474 ON mcm.conversationid = m.conversationid
475 LEFT JOIN {message_user_actions} mua
476 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
477 LEFT JOIN {message_contacts} mc
478 ON (mc.userid = ? AND mc.contactid = u.id)
480 AND mcm.userid != m.useridfrom
484 GROUP BY $userfields";
486 return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid],
487 $limitfrom, $limitnum);
491 * Returns the messages to display in the message area.
493 * @param int $userid the current user
494 * @param int $otheruserid the other user
495 * @param int $limitfrom
496 * @param int $limitnum
497 * @param string $sort
498 * @param int $timefrom the time from the message being sent
499 * @param int $timeto the time up until the message being sent
502 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
503 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
505 if (!empty($timefrom)) {
506 // Check the cache to see if we even need to do a DB query.
507 $cache = \cache::make('core', 'message_time_last_message_between_users');
508 $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
509 $lastcreated = $cache->get($key);
511 // The last known message time is earlier than the one being requested so we can
512 // just return an empty result set rather than having to query the DB.
513 if ($lastcreated && $lastcreated < $timefrom) {
518 $arrmessages = array();
519 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
520 $sort, $timefrom, $timeto)) {
522 $arrmessages = helper::create_messages($userid, $messages);
529 * Returns the most recent message between two users.
531 * @param int $userid the current user
532 * @param int $otheruserid the other user
533 * @return \stdClass|null
535 public static function get_most_recent_message($userid, $otheruserid) {
536 // We want two messages here so we get an accurate 'blocktime' value.
537 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
538 // Swap the order so we now have them in historical order.
539 $messages = array_reverse($messages);
540 $arrmessages = helper::create_messages($userid, $messages);
541 return array_pop($arrmessages);
548 * Returns the profile information for a contact for a user.
550 * @param int $userid The user id
551 * @param int $otheruserid The id of the user whose profile we want to view.
554 public static function get_profile($userid, $otheruserid) {
555 global $CFG, $DB, $PAGE;
557 require_once($CFG->dirroot . '/user/lib.php');
559 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
561 // Create the data we are going to pass to the renderable.
562 $data = new \stdClass();
563 $data->userid = $otheruserid;
564 $data->fullname = fullname($user);
568 $data->isonline = null;
569 // Get the user picture data - messaging has always shown these to the user.
570 $userpicture = new \user_picture($user);
571 $userpicture->size = 1; // Size f1.
572 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
573 $userpicture->size = 0; // Size f2.
574 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
576 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
578 if (isset($userfields['city'])) {
579 $data->city = $userfields['city'];
581 if (isset($userfields['country'])) {
582 $data->country = $userfields['country'];
584 if (isset($userfields['email'])) {
585 $data->email = $userfields['email'];
587 if (isset($userfields['lastaccess'])) {
588 $data->isonline = helper::is_online($userfields['lastaccess']);
592 // Check if the contact has been blocked.
593 $contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $otheruserid));
595 $data->isblocked = (bool) $contact->blocked;
596 $data->iscontact = true;
598 $data->isblocked = false;
599 $data->iscontact = false;
606 * Checks if a user can delete messages they have either received or sent.
608 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
609 * but will still seem as if it was by the user)
610 * @return bool Returns true if a user can delete the conversation, false otherwise.
612 public static function can_delete_conversation($userid) {
615 $systemcontext = \context_system::instance();
617 // Let's check if the user is allowed to delete this conversation.
618 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
619 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
620 $USER->id == $userid))) {
628 * Deletes a conversation.
630 * This function does not verify any permissions.
632 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
633 * but will still seem as if it was by the user)
634 * @param int $otheruserid The id of the other user in the conversation
637 public static function delete_conversation($userid, $otheruserid) {
640 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
642 // If there is no conversation, there is nothing to do.
643 if (!$conversationid) {
647 // Get all messages belonging to this conversation that have not already been deleted by this user.
650 INNER JOIN {message_conversations} mc
651 ON m.conversationid = mc.id
652 LEFT JOIN {message_user_actions} mua
653 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
656 ORDER BY m.timecreated ASC";
657 $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
659 // Ok, mark these as deleted.
660 foreach ($messages as $message) {
661 $mua = new \stdClass();
662 $mua->userid = $userid;
663 $mua->messageid = $message->id;
664 $mua->action = self::MESSAGE_ACTION_DELETED;
665 $mua->timecreated = time();
666 $mua->id = $DB->insert_record('message_user_actions', $mua);
668 if ($message->useridfrom == $userid) {
669 $useridto = $otheruserid;
673 \core\event\message_deleted::create_from_ids($message->useridfrom, $useridto,
674 $USER->id, $message->id, $mua->id)->trigger();
681 * Returns the count of unread conversations (collection of messages from a single user) for
684 * @param \stdClass $user the user who's conversations should be counted
685 * @return int the count of the user's unread conversations
687 public static function count_unread_conversations($user = null) {
694 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
696 INNER JOIN {message_conversations} mc
697 ON m.conversationid = mc.id
698 INNER JOIN {message_conversation_members} mcm
699 ON mc.id = mcm.conversationid
700 LEFT JOIN {message_user_actions} mua
701 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
703 AND mcm.userid != m.useridfrom
706 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
710 * Marks all messages being sent to a user in a particular conversation.
712 * If $conversationdid is null then it marks all messages as read sent to $userid.
715 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
717 public static function mark_all_messages_as_read($userid, $conversationid = null) {
720 $messagesql = "SELECT m.*
722 INNER JOIN {message_conversations} mc
723 ON mc.id = m.conversationid
724 INNER JOIN {message_conversation_members} mcm
725 ON mcm.conversationid = mc.id
727 AND m.useridfrom != ?";
728 $messageparams[] = $userid;
729 $messageparams[] = $userid;
730 if (!is_null($conversationid)) {
731 $messagesql .= " AND mc.id = ?";
732 $messageparams[] = $conversationid;
735 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
736 foreach ($messages as $message) {
737 self::mark_message_as_read($userid, $message);
743 * Marks all notifications being sent from one user to another user as read.
745 * If the from user is null then it marks all notifications as read sent to the to user.
747 * @param int $touserid the id of the message recipient
748 * @param int|null $fromuserid the id of the message sender, null if all messages
751 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
754 $notificationsql = "SELECT n.*
755 FROM {notifications} n
757 AND timeread is NULL";
758 $notificationsparams = [$touserid];
759 if (!empty($fromuserid)) {
760 $notificationsql .= " AND useridfrom = ?";
761 $notificationsparams[] = $fromuserid;
764 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
765 foreach ($notifications as $notification) {
766 self::mark_notification_as_read($notification);
768 $notifications->close();
772 * Marks ALL messages being sent from $fromuserid to $touserid as read.
774 * Can be filtered by type.
776 * @deprecated since 3.5
777 * @param int $touserid the id of the message recipient
778 * @param int $fromuserid the id of the message sender
779 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
782 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
783 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
784 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
787 $type = strtolower($type);
789 $conversationid = null;
790 $ignoremessages = false;
791 if (!empty($fromuserid)) {
792 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
793 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
794 $ignoremessages = true;
799 if ($type == MESSAGE_TYPE_NOTIFICATION) {
800 self::mark_all_notifications_as_read($touserid, $fromuserid);
801 } else if ($type == MESSAGE_TYPE_MESSAGE) {
802 if (!$ignoremessages) {
803 self::mark_all_messages_as_read($touserid, $conversationid);
806 } else { // We want both.
807 self::mark_all_notifications_as_read($touserid, $fromuserid);
808 if (!$ignoremessages) {
809 self::mark_all_messages_as_read($touserid, $conversationid);
815 * Returns message preferences.
817 * @param array $processors
818 * @param array $providers
819 * @param \stdClass $user
823 public static function get_all_message_preferences($processors, $providers, $user) {
824 $preferences = helper::get_providers_preferences($providers, $user->id);
825 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
827 // For every processors put its options on the form (need to get function from processor's lib.php).
828 foreach ($processors as $processor) {
829 $processor->object->load_data($preferences, $user->id);
832 // Load general messaging preferences.
833 $preferences->blocknoncontacts = get_user_preferences('message_blocknoncontacts', '', $user->id);
834 $preferences->mailformat = $user->mailformat;
835 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
841 * Count the number of users blocked by a user.
843 * @param \stdClass $user The user object
844 * @return int the number of blocked users
846 public static function count_blocked_users($user = null) {
853 $sql = "SELECT count(mc.id)
854 FROM {message_contacts} mc
855 WHERE mc.userid = :userid AND mc.blocked = 1";
856 return $DB->count_records_sql($sql, array('userid' => $user->id));
860 * Determines if a user is permitted to send another user a private message.
861 * If no sender is provided then it defaults to the logged in user.
863 * @param \stdClass $recipient The user object.
864 * @param \stdClass|null $sender The user object.
865 * @return bool true if user is permitted, false otherwise.
867 public static function can_post_message($recipient, $sender = null) {
870 if (is_null($sender)) {
871 // The message is from the logged in user, unless otherwise specified.
875 if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
879 // The recipient blocks messages from non-contacts and the
880 // sender isn't a contact.
881 if (self::is_user_non_contact_blocked($recipient, $sender)) {
886 if ($sender !== null && isset($sender->id)) {
887 $senderid = $sender->id;
889 // The recipient has specifically blocked this sender.
890 if (self::is_user_blocked($recipient->id, $senderid)) {
898 * Checks if the recipient is allowing messages from users that aren't a
899 * contact. If not then it checks to make sure the sender is in the
900 * recipient's contacts.
902 * @param \stdClass $recipient The user object.
903 * @param \stdClass|null $sender The user object.
904 * @return bool true if $sender is blocked, false otherwise.
906 public static function is_user_non_contact_blocked($recipient, $sender = null) {
909 if (is_null($sender)) {
910 // The message is from the logged in user, unless otherwise specified.
914 $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
915 if (!empty($blockednoncontacts)) {
916 // Confirm the sender is a contact of the recipient.
917 $exists = $DB->record_exists('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id));
919 // All good, the recipient is a contact of the sender.
922 // Oh no, the recipient is not a contact. Looks like we can't send the message.
931 * Checks if the recipient has specifically blocked the sending user.
933 * Note: This function will always return false if the sender has the
934 * readallmessages capability at the system context level.
936 * @param int $recipientid User ID of the recipient.
937 * @param int $senderid User ID of the sender.
938 * @return bool true if $sender is blocked, false otherwise.
940 public static function is_user_blocked($recipientid, $senderid = null) {
943 if (is_null($senderid)) {
944 // The message is from the logged in user, unless otherwise specified.
945 $senderid = $USER->id;
948 $systemcontext = \context_system::instance();
949 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
953 if ($DB->get_field('message_contacts', 'blocked', ['userid' => $recipientid, 'contactid' => $senderid])) {
961 * Get specified message processor, validate corresponding plugin existence and
962 * system configuration.
964 * @param string $name Name of the processor.
965 * @param bool $ready only return ready-to-use processors.
966 * @return mixed $processor if processor present else empty array.
969 public static function get_message_processor($name, $ready = false) {
972 $processor = $DB->get_record('message_processors', array('name' => $name));
973 if (empty($processor)) {
974 // Processor not found, return.
978 $processor = self::get_processed_processor_object($processor);
980 if ($processor->enabled && $processor->configured) {
991 * Returns weather a given processor is enabled or not.
992 * Note:- This doesn't check if the processor is configured or not.
994 * @param string $name Name of the processor
997 public static function is_processor_enabled($name) {
999 $cache = \cache::make('core', 'message_processors_enabled');
1000 $status = $cache->get($name);
1002 if ($status === false) {
1003 $processor = self::get_message_processor($name);
1004 if (!empty($processor)) {
1005 $cache->set($name, $processor->enabled);
1006 return $processor->enabled;
1016 * Set status of a processor.
1018 * @param \stdClass $processor processor record.
1019 * @param 0|1 $enabled 0 or 1 to set the processor status.
1023 public static function update_processor_status($processor, $enabled) {
1025 $cache = \cache::make('core', 'message_processors_enabled');
1026 $cache->delete($processor->name);
1027 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1031 * Given a processor object, loads information about it's settings and configurations.
1032 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1033 * or @see \get_message_processors()
1035 * @param \stdClass $processor processor object
1036 * @return \stdClass processed processor object
1039 public static function get_processed_processor_object(\stdClass $processor) {
1042 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1043 if (is_readable($processorfile)) {
1044 include_once($processorfile);
1045 $processclass = 'message_output_' . $processor->name;
1046 if (class_exists($processclass)) {
1047 $pclass = new $processclass();
1048 $processor->object = $pclass;
1049 $processor->configured = 0;
1050 if ($pclass->is_system_configured()) {
1051 $processor->configured = 1;
1053 $processor->hassettings = 0;
1054 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1055 $processor->hassettings = 1;
1057 $processor->available = 1;
1059 print_error('errorcallingprocessor', 'message');
1062 $processor->available = 0;
1068 * Retrieve users blocked by $user1
1070 * @param int $userid The user id of the user whos blocked users we are returning
1071 * @return array the users blocked
1073 public static function get_blocked_users($userid) {
1076 $userfields = \user_picture::fields('u', array('lastaccess'));
1077 $blockeduserssql = "SELECT $userfields
1078 FROM {message_contacts} mc
1080 ON u.id = mc.contactid
1084 GROUP BY $userfields
1085 ORDER BY u.firstname ASC";
1086 return $DB->get_records_sql($blockeduserssql, [$userid]);
1090 * Mark a single message as read.
1092 * @param int $userid The user id who marked the message as read
1093 * @param \stdClass $message The message
1094 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1096 public static function mark_message_as_read($userid, $message, $timeread = null) {
1099 if (is_null($timeread)) {
1103 // Check if the user has already read this message.
1104 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1105 'messageid' => $message->id, 'action' => self::MESSAGE_ACTION_READ])) {
1106 $mua = new \stdClass();
1107 $mua->userid = $userid;
1108 $mua->messageid = $message->id;
1109 $mua->action = self::MESSAGE_ACTION_READ;
1110 $mua->timecreated = $timeread;
1111 $mua->id = $DB->insert_record('message_user_actions', $mua);
1113 // Get the context for the user who received the message.
1114 $context = \context_user::instance($userid, IGNORE_MISSING);
1115 // If the user no longer exists the context value will be false, in this case use the system context.
1116 if ($context === false) {
1117 $context = \context_system::instance();
1120 // Trigger event for reading a message.
1121 $event = \core\event\message_viewed::create(array(
1122 'objectid' => $mua->id,
1123 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1124 'context' => $context,
1125 'relateduserid' => $message->useridfrom,
1127 'messageid' => $message->id
1135 * Mark a single notification as read.
1137 * @param \stdClass $notification The notification
1138 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1140 public static function mark_notification_as_read($notification, $timeread = null) {
1143 if (is_null($timeread)) {
1147 if (is_null($notification->timeread)) {
1148 $updatenotification = new \stdClass();
1149 $updatenotification->id = $notification->id;
1150 $updatenotification->timeread = $timeread;
1152 $DB->update_record('notifications', $updatenotification);
1154 // Trigger event for reading a notification.
1155 \core\event\notification_viewed::create_from_ids(
1156 $notification->useridfrom,
1157 $notification->useridto,
1164 * Checks if a user can delete a message.
1166 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1167 * but will still seem as if it was by the user)
1168 * @param int $messageid The message id
1169 * @return bool Returns true if a user can delete the message, false otherwise.
1171 public static function can_delete_message($userid, $messageid) {
1174 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1176 INNER JOIN {message_conversations} mc
1177 ON m.conversationid = mc.id
1178 INNER JOIN {message_conversation_members} mcm
1179 ON mcm.conversationid = mc.id
1180 WHERE mcm.userid != m.useridfrom
1182 $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1184 if ($message->useridfrom == $userid) {
1185 $userdeleting = 'useridfrom';
1186 } else if ($message->useridto == $userid) {
1187 $userdeleting = 'useridto';
1192 $systemcontext = \context_system::instance();
1194 // Let's check if the user is allowed to delete this message.
1195 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
1196 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1197 $USER->id == $message->$userdeleting))) {
1205 * Deletes a message.
1207 * This function does not verify any permissions.
1209 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1210 * but will still seem as if it was by the user)
1211 * @param int $messageid The message id
1214 public static function delete_message($userid, $messageid) {
1217 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1219 INNER JOIN {message_conversations} mc
1220 ON m.conversationid = mc.id
1221 INNER JOIN {message_conversation_members} mcm
1222 ON mcm.conversationid = mc.id
1223 WHERE mcm.userid != m.useridfrom
1225 $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1227 // Check if the user has already deleted this message.
1228 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1229 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1230 $mua = new \stdClass();
1231 $mua->userid = $userid;
1232 $mua->messageid = $messageid;
1233 $mua->action = self::MESSAGE_ACTION_DELETED;
1234 $mua->timecreated = time();
1235 $mua->id = $DB->insert_record('message_user_actions', $mua);
1237 // Trigger event for deleting a message.
1238 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1239 $userid, $message->id, $mua->id)->trigger();
1248 * Returns the conversation between two users.
1250 * @param array $userids
1251 * @return int|bool The id of the conversation, false if not found
1253 public static function get_conversation_between_users(array $userids) {
1256 $hash = helper::get_conversation_hash($userids);
1258 if ($conversation = $DB->get_record('message_conversations', ['convhash' => $hash])) {
1259 return $conversation->id;
1266 * Creates a conversation between two users.
1268 * @param array $userids
1269 * @return int The id of the conversation
1271 public static function create_conversation_between_users(array $userids) {
1274 $conversation = new \stdClass();
1275 $conversation->convhash = helper::get_conversation_hash($userids);
1276 $conversation->timecreated = time();
1277 $conversation->id = $DB->insert_record('message_conversations', $conversation);
1279 // Add members to this conversation.
1280 foreach ($userids as $userid) {
1281 $member = new \stdClass();
1282 $member->conversationid = $conversation->id;
1283 $member->userid = $userid;
1284 $member->timecreated = time();
1285 $DB->insert_record('message_conversation_members', $member);
1288 return $conversation->id;