6424ad08829042ed25813a5fadd9c66f6eb203e7
[moodle.git] / message / classes / api.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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.
13 //
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/>.
17 /**
18  * Contains class used to return information to display for the message area.
19  *
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
23  */
25 namespace core_message;
27 use core_favourites\local\entity\favourite;
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->dirroot . '/lib/messagelib.php');
33 /**
34  * Class used to return information to display for the message area.
35  *
36  * @copyright  2016 Mark Nelson <markn@moodle.com>
37  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38  */
39 class api {
41     /**
42      * The action for reading a message.
43      */
44     const MESSAGE_ACTION_READ = 1;
46     /**
47      * The action for deleting a message.
48      */
49     const MESSAGE_ACTION_DELETED = 2;
51     /**
52      * The privacy setting for being messaged by anyone within courses user is member of.
53      */
54     const MESSAGE_PRIVACY_COURSEMEMBER = 0;
56     /**
57      * The privacy setting for being messaged only by contacts.
58      */
59     const MESSAGE_PRIVACY_ONLYCONTACTS = 1;
61     /**
62      * The privacy setting for being messaged by anyone on the site.
63      */
64     const MESSAGE_PRIVACY_SITE = 2;
66     /**
67      * An individual conversation.
68      */
69     const MESSAGE_CONVERSATION_TYPE_INDIVIDUAL = 1;
71     /**
72      * A group conversation.
73      */
74     const MESSAGE_CONVERSATION_TYPE_GROUP = 2;
76     /**
77      * The state for an enabled conversation area.
78      */
79     const MESSAGE_CONVERSATION_ENABLED = 1;
81     /**
82      * The state for a disabled conversation area.
83      */
84     const MESSAGE_CONVERSATION_DISABLED = 0;
86     /**
87      * Handles searching for messages in the message area.
88      *
89      * @param int $userid The user id doing the searching
90      * @param string $search The string the user is searching
91      * @param int $limitfrom
92      * @param int $limitnum
93      * @return array
94      */
95     public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
96         global $DB;
98         // Get the user fields we want.
99         $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
100         $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
102         $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto, m.subject, m.fullmessage, m.fullmessagehtml, m.fullmessageformat,
103                        m.smallmessage, m.timecreated, 0 as isread, $ufields, mub.id as userfrom_blocked, $ufields2,
104                        mub2.id as userto_blocked
105                   FROM {messages} m
106             INNER JOIN {user} u
107                     ON u.id = m.useridfrom
108             INNER JOIN {message_conversations} mc
109                     ON mc.id = m.conversationid
110             INNER JOIN {message_conversation_members} mcm
111                     ON mcm.conversationid = m.conversationid
112             INNER JOIN {user} u2
113                     ON u2.id = mcm.userid
114              LEFT JOIN {message_users_blocked} mub
115                     ON (mub.blockeduserid = u.id AND mub.userid = ?)
116              LEFT JOIN {message_users_blocked} mub2
117                     ON (mub2.blockeduserid = u2.id AND mub2.userid = ?)
118              LEFT JOIN {message_user_actions} mua
119                     ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
120                  WHERE (m.useridfrom = ? OR mcm.userid = ?)
121                    AND m.useridfrom != mcm.userid
122                    AND u.deleted = 0
123                    AND u2.deleted = 0
124                    AND mua.id is NULL
125                    AND " . $DB->sql_like('smallmessage', '?', false) . "
126               ORDER BY timecreated DESC";
128         $params = array($userid, $userid, $userid, self::MESSAGE_ACTION_DELETED, $userid, $userid, '%' . $search . '%');
130         // Convert the messages into searchable contacts with their last message being the message that was searched.
131         $conversations = array();
132         if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
133             foreach ($messages as $message) {
134                 $prefix = 'userfrom_';
135                 if ($userid == $message->useridfrom) {
136                     $prefix = 'userto_';
137                     // If it from the user, then mark it as read, even if it wasn't by the receiver.
138                     $message->isread = true;
139                 }
140                 $blockedcol = $prefix . 'blocked';
141                 $message->blocked = $message->$blockedcol ? 1 : 0;
143                 $message->messageid = $message->id;
144                 $conversations[] = helper::create_contact($message, $prefix);
145             }
146         }
148         return $conversations;
149     }
151     /**
152      * Handles searching for user in a particular course in the message area.
153      *
154      * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
155      * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
156      * But we are deprecating data_for_messagearea_search_users_in_course external function.
157      * Followup: MDL-63915
158      *
159      * @param int $userid The user id doing the searching
160      * @param int $courseid The id of the course we are searching in
161      * @param string $search The string the user is searching
162      * @param int $limitfrom
163      * @param int $limitnum
164      * @return array
165      */
166     public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
167         global $DB;
169         // Get all the users in the course.
170         list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
171         $sql = "SELECT u.*, mub.id as isblocked
172                   FROM {user} u
173                   JOIN ($esql) je
174                     ON je.id = u.id
175              LEFT JOIN {message_users_blocked} mub
176                     ON (mub.blockeduserid = u.id AND mub.userid = :userid)
177                  WHERE u.deleted = 0";
178         // Add more conditions.
179         $fullname = $DB->sql_fullname();
180         $sql .= " AND u.id != :userid2
181                   AND " . $DB->sql_like($fullname, ':search', false) . "
182              ORDER BY " . $DB->sql_fullname();
183         $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
185         // Convert all the user records into contacts.
186         $contacts = array();
187         if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
188             foreach ($users as $user) {
189                 $user->blocked = $user->isblocked ? 1 : 0;
190                 $contacts[] = helper::create_contact($user);
191             }
192         }
194         return $contacts;
195     }
197     /**
198      * Handles searching for user in the message area.
199      *
200      * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
201      * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
202      * But we are deprecating data_for_messagearea_search_users external function.
203      * Followup: MDL-63915
204      *
205      * @param int $userid The user id doing the searching
206      * @param string $search The string the user is searching
207      * @param int $limitnum
208      * @return array
209      */
210     public static function search_users($userid, $search, $limitnum = 0) {
211         global $CFG, $DB;
213         // Used to search for contacts.
214         $fullname = $DB->sql_fullname();
215         $ufields = \user_picture::fields('u', array('lastaccess'));
217         // Users not to include.
218         $excludeusers = array($userid, $CFG->siteguest);
219         list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
221         // Ok, let's search for contacts first.
222         $contacts = array();
223         $sql = "SELECT $ufields, mub.id as isuserblocked
224                   FROM {user} u
225                   JOIN {message_contacts} mc
226                     ON u.id = mc.contactid
227              LEFT JOIN {message_users_blocked} mub
228                     ON (mub.userid = :userid2 AND mub.blockeduserid = u.id)
229                  WHERE mc.userid = :userid
230                    AND u.deleted = 0
231                    AND u.confirmed = 1
232                    AND " . $DB->sql_like($fullname, ':search', false) . "
233                    AND u.id $exclude
234               ORDER BY " . $DB->sql_fullname();
235         if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'userid2' => $userid,
236                 'search' => '%' . $search . '%') + $excludeparams, 0, $limitnum)) {
237             foreach ($users as $user) {
238                 $user->blocked = $user->isuserblocked ? 1 : 0;
239                 $contacts[] = helper::create_contact($user);
240             }
241         }
243         // Now, let's get the courses.
244         // Make sure to limit searches to enrolled courses.
245         $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
246         $courses = array();
247         // Really we want the user to be able to view the participants if they have the capability
248         // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
249         // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
250         // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
251         if ($arrcourses = \core_course_category::search_courses(array('search' => $search), array('limit' => $limitnum),
252                 array('moodle/course:viewparticipants'))) {
253             foreach ($arrcourses as $course) {
254                 if (isset($enrolledcourses[$course->id])) {
255                     $data = new \stdClass();
256                     $data->id = $course->id;
257                     $data->shortname = $course->shortname;
258                     $data->fullname = $course->fullname;
259                     $courses[] = $data;
260                 }
261             }
262         }
264         // Let's get those non-contacts. Toast them gears boi.
265         // Note - you can only block contacts, so these users will not be blocked, so no need to get that
266         // extra detail from the database.
267         $noncontacts = array();
268         $sql = "SELECT $ufields
269                   FROM {user} u
270                  WHERE u.deleted = 0
271                    AND u.confirmed = 1
272                    AND " . $DB->sql_like($fullname, ':search', false) . "
273                    AND u.id $exclude
274                    AND u.id NOT IN (SELECT contactid
275                                       FROM {message_contacts}
276                                      WHERE userid = :userid)
277               ORDER BY " . $DB->sql_fullname();
278         if ($users = $DB->get_records_sql($sql,  array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
279                 0, $limitnum)) {
280             foreach ($users as $user) {
281                 $noncontacts[] = helper::create_contact($user);
282             }
283         }
285         return array($contacts, $courses, $noncontacts);
286     }
288     /**
289      * Handles searching for user.
290      *
291      * @param int $userid The user id doing the searching
292      * @param string $search The string the user is searching
293      * @param int $limitfrom
294      * @param int $limitnum
295      * @return array
296      */
297     public static function message_search_users(int $userid, string $search, int $limitfrom = 0, int $limitnum = 20) : array {
298         global $CFG, $DB;
300         // Check if messaging is enabled.
301         if (empty($CFG->messaging)) {
302             throw new \moodle_exception('disabled', 'message');
303         }
305         // Used to search for contacts.
306         $fullname = $DB->sql_fullname();
308         // Users not to include.
309         $excludeusers = array($userid, $CFG->siteguest);
310         list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
312         $params = array('search' => '%' . $search . '%', 'userid1' => $userid, 'userid2' => $userid);
314         // Ok, let's search for contacts first.
315         $sql = "SELECT u.id
316                   FROM {user} u
317                   JOIN {message_contacts} mc
318                     ON (u.id = mc.contactid AND mc.userid = :userid1) OR (u.id = mc.userid AND mc.contactid = :userid2)
319                  WHERE u.deleted = 0
320                    AND u.confirmed = 1
321                    AND " . $DB->sql_like($fullname, ':search', false) . "
322                    AND u.id $exclude
323               ORDER BY " . $DB->sql_fullname();
324         $foundusers = $DB->get_records_sql_menu($sql, $params + $excludeparams, $limitfrom, $limitnum);
326         $orderedcontacts = array();
327         if (!empty($foundusers)) {
328             $contacts = helper::get_member_info($userid, array_keys($foundusers));
329             // The get_member_info returns an associative array, so is not ordered in the same way.
330             // We need to reorder it again based on query's result.
331             foreach ($foundusers as $key => $value) {
332                 $contact = $contacts[$key];
333                 $contact->conversations = self::get_conversations_between_users($userid, $key, 0, 1000);
334                 $orderedcontacts[] = $contact;
335             }
336         }
338         // Let's get those non-contacts.
339         // If site wide messaging is enabled, we just fetch any matched users which are non-contacts.
340         if ($CFG->messagingallusers) {
341             $sql = "SELECT u.id
342                   FROM {user} u
343                  WHERE u.deleted = 0
344                    AND u.confirmed = 1
345                    AND " . $DB->sql_like($fullname, ':search', false) . "
346                    AND u.id $exclude
347                    AND NOT EXISTS (SELECT mc.id
348                                      FROM {message_contacts} mc
349                                     WHERE (mc.userid = u.id AND mc.contactid = :userid1)
350                                        OR (mc.userid = :userid2 AND mc.contactid = u.id))
351               ORDER BY " . $DB->sql_fullname();
353             $foundusers = $DB->get_records_sql($sql, $params + $excludeparams, $limitfrom, $limitnum);
354         } else {
355             require_once($CFG->dirroot . '/user/lib.php');
356             // If site-wide messaging is disabled, then we should only be able to search for users who we are allowed to see.
357             // Because we can't achieve all the required visibility checks in SQL, we'll iterate through the non-contact records
358             // and stop once we have enough matching the 'visible' criteria.
359             // TODO: MDL-63983 - Improve the performance of non-contact searches when site-wide messaging is disabled (default).
361             // Use a local generator to achieve this iteration.
362             $getnoncontactusers = function ($limitfrom = 0, $limitnum = 0) use($fullname, $exclude, $params, $excludeparams) {
363                 global $DB;
364                 $sql = "SELECT u.*
365                       FROM {user} u
366                      WHERE u.deleted = 0
367                        AND u.confirmed = 1
368                        AND " . $DB->sql_like($fullname, ':search', false) . "
369                        AND u.id $exclude
370                        AND NOT EXISTS (SELECT mc.id
371                                          FROM {message_contacts} mc
372                                         WHERE (mc.userid = u.id AND mc.contactid = :userid1)
373                                            OR (mc.userid = :userid2 AND mc.contactid = u.id))
374                   ORDER BY " . $DB->sql_fullname();
375                 while ($records = $DB->get_records_sql($sql, $params + $excludeparams, $limitfrom, $limitnum)) {
376                     yield $records;
377                     $limitfrom += $limitnum;
378                 }
379             };
381             // Fetch in batches of $limitnum * 2 to improve the chances of matching a user without going back to the DB.
382             // The generator cannot function without a sensible limiter, so set one if this is not set.
383             $batchlimit = ($limitnum == 0) ? 20 : $limitnum;
385             // We need to make the offset param work with the generator.
386             // Basically, if we want to get say 10 records starting at the 40th record, we need to see 50 records and return only
387             // those after the 40th record. We can never pass the method's offset param to the generator as we need to manage the
388             // position within those valid records ourselves.
389             // See MDL-63983 dealing with performance improvements to this area of code.
390             $noofvalidseenrecords = 0;
391             $returnedusers = [];
392             foreach ($getnoncontactusers(0, $batchlimit) as $users) {
393                 foreach ($users as $id => $user) {
394                     $userdetails = \user_get_user_details_courses($user);
396                     // Return the user only if the searched field is returned.
397                     // Otherwise it means that the $USER was not allowed to search the returned user.
398                     if (!empty($userdetails) and !empty($userdetails['fullname'])) {
399                         // We know we've matched, but only save the record if it's within the offset area we need.
400                         if ($limitfrom == 0) {
401                             // No offset specified, so just save.
402                             $returnedusers[$id] = $user;
403                         } else {
404                             // There is an offset in play.
405                             // If we've passed enough records already (> offset value), then we can save this one.
406                             if ($noofvalidseenrecords >= $limitfrom) {
407                                 $returnedusers[$id] = $user;
408                             }
409                         }
410                         if (count($returnedusers) == $limitnum) {
411                             break 2;
412                         }
413                         $noofvalidseenrecords++;
414                     }
415                 }
416             }
417             $foundusers = $returnedusers;
418         }
420         $orderednoncontacts = array();
421         if (!empty($foundusers)) {
422             $noncontacts = helper::get_member_info($userid, array_keys($foundusers));
423             // The get_member_info returns an associative array, so is not ordered in the same way.
424             // We need to reorder it again based on query's result.
425             foreach ($foundusers as $key => $value) {
426                 $contact = $noncontacts[$key];
427                 $contact->conversations = self::get_conversations_between_users($userid, $key, 0, 1000);
428                 $orderednoncontacts[] = $contact;
429             }
430         }
432         return array($orderedcontacts, $orderednoncontacts);
433     }
435     /**
436      * Gets extra fields, like image url and subname for any conversations linked to components.
437      *
438      * The subname is like a subtitle for the conversation, to compliment it's name.
439      * The imageurl is the location of the image for the conversation, as might be seen on a listing of conversations for a user.
440      *
441      * @param array $conversations a list of conversations records.
442      * @return array the array of subnames, index by conversation id.
443      * @throws \coding_exception
444      * @throws \dml_exception
445      */
446     protected static function get_linked_conversation_extra_fields(array $conversations) : array {
447         global $DB;
449         $linkedconversations = [];
450         foreach ($conversations as $conversation) {
451             if (!is_null($conversation->component) && !is_null($conversation->itemtype)) {
452                 $linkedconversations[$conversation->component][$conversation->itemtype][$conversation->id]
453                     = $conversation->itemid;
454             }
455         }
456         if (empty($linkedconversations)) {
457             return [];
458         }
460         // TODO: MDL-63814: Working out the subname for linked conversations should be done in a generic way.
461         // Get the itemid, but only for course group linked conversation for now.
462         $extrafields = [];
463         if (!empty($linkeditems = $linkedconversations['core_group']['groups'])) { // Format: [conversationid => itemid].
464             // Get the name of the course to which the group belongs.
465             list ($groupidsql, $groupidparams) = $DB->get_in_or_equal(array_values($linkeditems), SQL_PARAMS_NAMED, 'groupid');
466             $sql = "SELECT g.*, c.shortname as courseshortname
467                       FROM {groups} g
468                       JOIN {course} c
469                         ON g.courseid = c.id
470                      WHERE g.id $groupidsql";
471             $courseinfo = $DB->get_records_sql($sql, $groupidparams);
472             foreach ($linkeditems as $convid => $groupid) {
473                 if (array_key_exists($groupid, $courseinfo)) {
474                     $group = $courseinfo[$groupid];
475                     // Subname.
476                     $extrafields[$convid]['subname'] = format_string($courseinfo[$groupid]->courseshortname);
478                     // Imageurl.
479                     $extrafields[$convid]['imageurl'] = '';
480                     if ($url = get_group_picture_url($group, $group->courseid, true)) {
481                         $extrafields[$convid]['imageurl'] = $url->out(false);
482                     }
483                 }
484             }
485         }
486         return $extrafields;
487     }
490     /**
491      * Returns the contacts and their conversation to display in the contacts area.
492      *
493      * ** WARNING **
494      * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
495      * to retrieve too much information in a single call will cause performance problems.
496      * ** WARNING **
497      *
498      * This function has specifically been altered to break each of the data sets it
499      * requires into separate database calls. This is to avoid the performance problems
500      * observed when attempting to join large data sets (e.g. the message tables and
501      * the user table).
502      *
503      * While it is possible to gather the data in a single query, and it may even be
504      * more efficient with a correctly tuned database, we have opted to trade off some of
505      * the benefits of a single query in order to ensure this function will work on
506      * most databases with default tunings and with large data sets.
507      *
508      * @param int $userid The user id
509      * @param int $limitfrom
510      * @param int $limitnum
511      * @param int $type the type of the conversation, if you wish to filter to a certain type (see api constants).
512      * @param bool $favourites whether to include NO favourites (false) or ONLY favourites (true), or null to ignore this setting.
513      * @return array the array of conversations
514      * @throws \moodle_exception
515      */
516     public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20, int $type = null,
517             bool $favourites = null) {
518         global $DB;
520         if (!is_null($type) && !in_array($type, [self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
521                 self::MESSAGE_CONVERSATION_TYPE_GROUP])) {
522             throw new \moodle_exception("Invalid value ($type) for type param, please see api constants.");
523         }
525         // We need to know which conversations are favourites, so we can either:
526         // 1) Include the 'isfavourite' attribute on conversations (when $favourite = null and we're including all conversations)
527         // 2) Restrict the results to ONLY those conversations which are favourites (when $favourite = true)
528         // 3) Restrict the results to ONLY those conversations which are NOT favourites (when $favourite = false).
529         $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
530         $favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
531         $favouriteconversationids = array_column($favouriteconversations, 'itemid');
532         if ($favourites && empty($favouriteconversationids)) {
533             return []; // If we are aiming to return ONLY favourites, and we have none, there's nothing more to do.
534         }
536         // CONVERSATIONS AND MOST RECENT MESSAGE.
537         // Include those conversations with messages first (ordered by most recent message, desc), then add any conversations which
538         // don't have messages, such as newly created group conversations.
539         // Because we're sorting by message 'timecreated', those conversations without messages could be at either the start or the
540         // end of the results (behaviour for sorting of nulls differs between DB vendors), so we use the case to presort these.
542         // If we need to return ONLY favourites, or NO favourites, generate the SQL snippet.
543         $favouritesql = "";
544         $favouriteparams = [];
545         if (null !== $favourites && !empty($favouriteconversationids)) {
546             list ($insql, $favouriteparams) =
547                     $DB->get_in_or_equal($favouriteconversationids, SQL_PARAMS_NAMED, 'favouriteids', $favourites);
548             $favouritesql = " AND mc.id {$insql} ";
549         }
551         // If we need to restrict type, generate the SQL snippet.
552         $typesql = !is_null($type) ? " AND mc.type = :convtype " : "";
554         $sql = "SELECT m.id as messageid, mc.id as id, mc.name as conversationname, mc.type as conversationtype, m.useridfrom,
555                        m.smallmessage, m.fullmessage, m.fullmessageformat, m.fullmessagehtml, m.timecreated, mc.component,
556                        mc.itemtype, mc.itemid
557                   FROM {message_conversations} mc
558             INNER JOIN {message_conversation_members} mcm
559                     ON (mcm.conversationid = mc.id AND mcm.userid = :userid3)
560             LEFT JOIN (
561                           SELECT m.conversationid, MAX(m.id) AS messageid
562                             FROM {messages} m
563                       INNER JOIN (
564                                       SELECT m.conversationid, MAX(m.timecreated) as maxtime
565                                         FROM {messages} m
566                                   INNER JOIN {message_conversation_members} mcm
567                                           ON mcm.conversationid = m.conversationid
568                                    LEFT JOIN {message_user_actions} mua
569                                           ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
570                                        WHERE mua.id is NULL
571                                          AND mcm.userid = :userid2
572                                     GROUP BY m.conversationid
573                                  ) maxmessage
574                                ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
575                          GROUP BY m.conversationid
576                        ) lastmessage
577                     ON lastmessage.conversationid = mc.id
578             LEFT JOIN {messages} m
579                    ON m.id = lastmessage.messageid
580                 WHERE mc.id IS NOT NULL $typesql $favouritesql
581               ORDER BY (CASE WHEN m.timecreated IS NULL THEN 0 ELSE 1 END) DESC, m.timecreated DESC, id DESC";
583         $params = array_merge($favouriteparams, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
584             'userid2' => $userid, 'userid3' => $userid, 'convtype' => $type]);
585         $conversationset = $DB->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
587         $conversations = [];
588         $members = [];
589         $individualmembers = [];
590         $groupmembers = [];
591         foreach ($conversationset as $conversation) {
592             $conversations[$conversation->id] = $conversation;
593             $members[$conversation->id] = [];
594         }
595         $conversationset->close();
597         // If there are no conversations found, then return early.
598         if (empty($conversations)) {
599             return [];
600         }
602         // COMPONENT-LINKED CONVERSATION FIELDS.
603         // Conversations linked to components may have extra information, such as:
604         // - subname: Essentially a subtitle for the conversation. So you'd have "name: subname".
605         // - imageurl: A URL to the image for the linked conversation.
606         // For now, this is ONLY course groups.
607         $convextrafields = self::get_linked_conversation_extra_fields($conversations);
609         // MEMBERS.
610         // Ideally, we want to get 1 member for each conversation, but this depends on the type and whether there is a recent
611         // message or not.
612         //
613         // For 'individual' type conversations between 2 users, regardless of who sent the last message,
614         // we want the details of the other member in the conversation (i.e. not the current user).
615         //
616         // For 'group' type conversations, we want the details of the member who sent the last message, if there is one.
617         // This can be the current user or another group member, but for groups without messages, this will be empty.
618         //
619         // This also means that if type filtering is specified and only group conversations are returned, we don't need this extra
620         // query to get the 'other' user as we already have that information.
622         // Work out which members we have already, and which ones we might need to fetch.
623         // If all the last messages were from another user, then we don't need to fetch anything further.
624         foreach ($conversations as $conversation) {
625             if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
626                 if (!is_null($conversation->useridfrom) && $conversation->useridfrom != $userid) {
627                     $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
628                     $individualmembers[$conversation->useridfrom] = $conversation->useridfrom;
629                 } else {
630                     $individualconversations[] = $conversation->id;
631                 }
632             } else if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
633                 // If we have a recent message, the sender is our member.
634                 if (!is_null($conversation->useridfrom)) {
635                     $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
636                     $groupmembers[$conversation->useridfrom] = $conversation->useridfrom;
637                 }
638             }
639         }
640         // If we need to fetch any member information for any of the individual conversations.
641         // This is the case if any of the individual conversations have a recent message sent by the current user.
642         if (!empty($individualconversations)) {
643             list ($icidinsql, $icidinparams) = $DB->get_in_or_equal($individualconversations, SQL_PARAMS_NAMED, 'convid');
644             $indmembersql = "SELECT mcm.id, mcm.conversationid, mcm.userid
645                         FROM {message_conversation_members} mcm
646                        WHERE mcm.conversationid $icidinsql
647                        AND mcm.userid != :userid
648                        ORDER BY mcm.id";
649             $indmemberparams = array_merge($icidinparams, ['userid' => $userid]);
650             $conversationmembers = $DB->get_records_sql($indmembersql, $indmemberparams);
652             foreach ($conversationmembers as $mid => $member) {
653                 $members[$member->conversationid][$member->userid] = $member->userid;
654                 $individualmembers[$member->userid] = $member->userid;
655             }
656         }
658         // We could fail early here if we're sure that:
659         // a) we have no otherusers for all the conversations (users may have been deleted)
660         // b) we're sure that all conversations are individual (1:1).
662         // We need to pull out the list of users info corresponding to the memberids in the conversations.This
663         // needs to be done in a separate query to avoid doing a join on the messages tables and the user
664         // tables because on large sites these tables are massive which results in extremely slow
665         // performance (typically due to join buffer exhaustion).
666         if (!empty($individualmembers) || !empty($groupmembers)) {
667             // Now, we want to remove any duplicates from the group members array. For individual members we will
668             // be doing a more extensive call as we want their contact requests as well as privacy information,
669             // which is not necessary for group conversations.
670             $diffgroupmembers = array_diff($groupmembers, $individualmembers);
672             $individualmemberinfo = helper::get_member_info($userid, $individualmembers, true, true);
673             $groupmemberinfo = helper::get_member_info($userid, $diffgroupmembers);
675             // Don't use array_merge, as we lose array keys.
676             $memberinfo = $individualmemberinfo + $groupmemberinfo;
678             // Update the members array with the member information.
679             $deletedmembers = [];
680             foreach ($members as $convid => $memberarr) {
681                 foreach ($memberarr as $key => $memberid) {
682                     if (array_key_exists($memberid, $memberinfo)) {
683                         // If the user is deleted, remember that.
684                         if ($memberinfo[$memberid]->isdeleted) {
685                             $deletedmembers[$convid][] = $memberid;
686                         }
688                         $members[$convid][$key] = clone $memberinfo[$memberid];
690                         if ($conversations[$convid]->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
691                             // Remove data we don't need for group.
692                             $members[$convid][$key]->requirescontact = null;
693                             $members[$convid][$key]->canmessage = null;
694                             $members[$convid][$key]->contactrequests = [];
695                         }
696                     }
697                 }
698             }
699         }
701         // MEMBER COUNT.
702         $cids = array_column($conversations, 'id');
703         list ($cidinsql, $cidinparams) = $DB->get_in_or_equal($cids, SQL_PARAMS_NAMED, 'convid');
704         $membercountsql = "SELECT conversationid, count(id) AS membercount
705                              FROM {message_conversation_members} mcm
706                             WHERE mcm.conversationid $cidinsql
707                          GROUP BY mcm.conversationid";
708         $membercounts = $DB->get_records_sql($membercountsql, $cidinparams);
710         // UNREAD MESSAGE COUNT.
711         // Finally, let's get the unread messages count for this user so that we can add it
712         // to the conversation. Remember we need to ignore the messages the user sent.
713         $unreadcountssql = 'SELECT m.conversationid, count(m.id) as unreadcount
714                               FROM {messages} m
715                         INNER JOIN {message_conversations} mc
716                                 ON mc.id = m.conversationid
717                         INNER JOIN {message_conversation_members} mcm
718                                 ON m.conversationid = mcm.conversationid
719                          LEFT JOIN {message_user_actions} mua
720                                 ON (mua.messageid = m.id AND mua.userid = ? AND
721                                    (mua.action = ? OR mua.action = ?))
722                              WHERE mcm.userid = ?
723                                AND m.useridfrom != ?
724                                AND mua.id is NULL
725                           GROUP BY m.conversationid';
726         $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
727             $userid, $userid]);
729         // Now, create the final return structure.
730         $arrconversations = [];
731         foreach ($conversations as $conversation) {
732             // Do not include any individual conversation which:
733             // a) Contains a deleted member or
734             // b) Does not contain a recent message for the user (this happens if the user has deleted all messages).
735             // Group conversations with deleted users or no messages are always returned.
736             if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL
737                     && (isset($deletedmembers[$conversation->id]) || empty($conversation->messageid))) {
738                 continue;
739             }
741             $conv = new \stdClass();
742             $conv->id = $conversation->id;
743             $conv->name = $conversation->conversationname;
744             $conv->subname = $convextrafields[$conv->id]['subname'] ?? null;
745             $conv->imageurl = $convextrafields[$conv->id]['imageurl'] ?? null;
746             $conv->type = $conversation->conversationtype;
747             $conv->membercount = $membercounts[$conv->id]->membercount;
748             $conv->isfavourite = in_array($conv->id, $favouriteconversationids);
749             $conv->isread = isset($unreadcounts[$conv->id]) ? false : true;
750             $conv->unreadcount = isset($unreadcounts[$conv->id]) ? $unreadcounts[$conv->id]->unreadcount : null;
751             $conv->members = $members[$conv->id];
753             // Add the most recent message information.
754             $conv->messages = [];
755             if ($conversation->smallmessage) {
756                 $msg = new \stdClass();
757                 $msg->id = $conversation->messageid;
758                 $msg->text = message_format_message_text($conversation);
759                 $msg->useridfrom = $conversation->useridfrom;
760                 $msg->timecreated = $conversation->timecreated;
761                 $conv->messages[] = $msg;
762             }
764             $arrconversations[] = $conv;
765         }
766         return $arrconversations;
767     }
769     /**
770      * Returns all conversations between two users
771      *
772      * @param int $userid1 One of the user's id
773      * @param int $userid2 The other user's id
774      * @param int $limitfrom
775      * @param int $limitnum
776      * @return array
777      * @throws \dml_exception
778      */
779     public static function get_conversations_between_users(int $userid1, int $userid2,
780                                                            int $limitfrom = 0, int $limitnum = 20) : array {
782         global $DB;
784         if ($userid1 == $userid2) {
785             return array();
786         }
788         // Get all conversation where both user1 and user2 are members.
789         // TODO: Add subname value. Waiting for definite table structure.
790         $sql = "SELECT mc.id, mc.type, mc.name, mc.timecreated
791                   FROM {message_conversations} mc
792             INNER JOIN {message_conversation_members} mcm1
793                     ON mc.id = mcm1.conversationid
794             INNER JOIN {message_conversation_members} mcm2
795                     ON mc.id = mcm2.conversationid
796                  WHERE mcm1.userid = :userid1
797                    AND mcm2.userid = :userid2
798                    AND mc.enabled != 0
799               ORDER BY mc.timecreated DESC";
801         return $DB->get_records_sql($sql, array('userid1' => $userid1, 'userid2' => $userid2), $limitfrom, $limitnum);
802     }
804     /**
805      * Return a conversation.
806      *
807      * @param int $userid The user id to get the conversation for
808      * @param int $conversationid The id of the conversation to fetch
809      * @param bool $includecontactrequests Should contact requests be included between members
810      * @param bool $includeprivacyinfo Should privacy info be included between members
811      * @param int $memberlimit Limit number of members to load
812      * @param int $memberoffset Offset members by this amount
813      * @param int $messagelimit Limit number of messages to load
814      * @param int $messageoffset Offset the messages
815      * @param bool $newestmessagesfirst Order messages by newest first
816      * @return \stdClass
817      */
818     public static function get_conversation(
819         int $userid,
820         int $conversationid,
821         bool $includecontactrequests = false,
822         bool $includeprivacyinfo = false,
823         int $memberlimit = 0,
824         int $memberoffset = 0,
825         int $messagelimit = 0,
826         int $messageoffset = 0,
827         bool $newestmessagesfirst = true
828     ) {
829         global $USER, $DB;
831         $systemcontext = \context_system::instance();
832         $canreadallmessages = has_capability('moodle/site:readallmessages', $systemcontext);
833         if (($USER->id != $userid) && !$canreadallmessages) {
834             throw new \moodle_exception('You do not have permission to perform this action.');
835         }
837         $conversation = $DB->get_record('message_conversations', ['id' => $conversationid]);
838         if (!$conversation) {
839             return null;
840         }
842         $isconversationmember = $DB->record_exists(
843             'message_conversation_members',
844             [
845                 'conversationid' => $conversationid,
846                 'userid' => $userid
847             ]
848         );
850         if (!$isconversationmember && !$canreadallmessages) {
851             throw new \moodle_exception('You do not have permission to view this conversation.');
852         }
854         $members = self::get_conversation_members(
855             $userid,
856             $conversationid,
857             $includecontactrequests,
858             $includeprivacyinfo,
859             $memberoffset,
860             $memberlimit
861         );
862         // Strip out the requesting user to match what get_conversations does.
863         $members = array_filter($members, function($member) use ($userid) {
864             return $member->id != $userid;
865         });
867         $messages = self::get_conversation_messages(
868             $userid,
869             $conversationid,
870             $messageoffset,
871             $messagelimit,
872             $newestmessagesfirst ? 'timecreated DESC' : 'timecreated ASC'
873         );
875         $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
876         $isfavourite = $service->favourite_exists('core_message', 'message_conversations', $conversationid, $systemcontext);
878         $convextrafields = self::get_linked_conversation_extra_fields([$conversation]);
879         $subname = isset($convextrafields[$conversationid]) ? $convextrafields[$conversationid]['subname'] : null;
880         $imageurl = isset($convextrafields[$conversationid]) ? $convextrafields[$conversationid]['imageurl'] : null;
882         $unreadcountssql = 'SELECT count(m.id)
883                               FROM {messages} m
884                         INNER JOIN {message_conversations} mc
885                                 ON mc.id = m.conversationid
886                          LEFT JOIN {message_user_actions} mua
887                                 ON (mua.messageid = m.id AND mua.userid = ? AND
888                                    (mua.action = ? OR mua.action = ?))
889                              WHERE m.conversationid = ?
890                                AND m.useridfrom != ?
891                                AND mua.id is NULL';
892         $unreadcount = $DB->count_records_sql(
893             $unreadcountssql,
894             [
895                 $userid,
896                 self::MESSAGE_ACTION_READ,
897                 self::MESSAGE_ACTION_DELETED,
898                 $conversationid,
899                 $userid
900             ]
901         );
903         $membercount = $DB->count_records('message_conversation_members', ['conversationid' => $conversationid]);
905         return (object) [
906             'id' => $conversation->id,
907             'name' => $conversation->name,
908             'subname' => $subname,
909             'imageurl' => $imageurl,
910             'type' => $conversation->type,
911             'membercount' => $membercount,
912             'isfavourite' => $isfavourite,
913             'isread' => empty($unreadcount),
914             'unreadcount' => $unreadcount,
915             'members' => $members,
916             'messages' => $messages['messages']
917         ];
918     }
920     /**
921      * Mark a conversation as a favourite for the given user.
922      *
923      * @param int $conversationid the id of the conversation to mark as a favourite.
924      * @param int $userid the id of the user to whom the favourite belongs.
925      * @return favourite the favourite object.
926      * @throws \moodle_exception if the user or conversation don't exist.
927      */
928     public static function set_favourite_conversation(int $conversationid, int $userid) : favourite {
929         if (!self::is_user_in_conversation($userid, $conversationid)) {
930             throw new \moodle_exception("Conversation doesn't exist or user is not a member");
931         }
932         $systemcontext = \context_system::instance();
933         $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
934         if ($favourite = $ufservice->get_favourite('core_message', 'message_conversations', $conversationid, $systemcontext)) {
935             return $favourite;
936         } else {
937             return $ufservice->create_favourite('core_message', 'message_conversations', $conversationid, $systemcontext);
938         }
939     }
941     /**
942      * Unset a conversation as a favourite for the given user.
943      *
944      * @param int $conversationid the id of the conversation to unset as a favourite.
945      * @param int $userid the id to whom the favourite belongs.
946      * @throws \moodle_exception if the favourite does not exist for the user.
947      */
948     public static function unset_favourite_conversation(int $conversationid, int $userid) {
949         $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
950         $ufservice->delete_favourite('core_message', 'message_conversations', $conversationid, \context_system::instance());
951     }
953     /**
954      * Returns the contacts to display in the contacts area.
955      *
956      * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
957      * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
958      * Followup: MDL-63915
959      *
960      * @param int $userid The user id
961      * @param int $limitfrom
962      * @param int $limitnum
963      * @return array
964      */
965     public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
966         global $DB;
968         $contactids = [];
969         $sql = "SELECT mc.*
970                   FROM {message_contacts} mc
971                  WHERE mc.userid = ? OR mc.contactid = ?
972               ORDER BY timecreated DESC";
973         if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
974             foreach ($contacts as $contact) {
975                 if ($userid == $contact->userid) {
976                     $contactids[] = $contact->contactid;
977                 } else {
978                     $contactids[] = $contact->userid;
979                 }
980             }
981         }
983         if (!empty($contactids)) {
984             list($insql, $inparams) = $DB->get_in_or_equal($contactids);
986             $sql = "SELECT u.*, mub.id as isblocked
987                       FROM {user} u
988                  LEFT JOIN {message_users_blocked} mub
989                         ON u.id = mub.blockeduserid
990                      WHERE u.id $insql";
991             if ($contacts = $DB->get_records_sql($sql, $inparams)) {
992                 $arrcontacts = [];
993                 foreach ($contacts as $contact) {
994                     $contact->blocked = $contact->isblocked ? 1 : 0;
995                     $arrcontacts[] = helper::create_contact($contact);
996                 }
998                 return $arrcontacts;
999             }
1000         }
1002         return [];
1003     }
1005     /**
1006      * Returns the contacts count.
1007      *
1008      * @param int $userid The user id
1009      * @return array
1010      */
1011     public static function count_contacts(int $userid) : int {
1012         global $DB;
1014         $sql = "SELECT COUNT(id)
1015                   FROM {message_contacts}
1016                  WHERE userid = ? OR contactid = ?";
1017         return $DB->count_records_sql($sql, [$userid, $userid]);
1018     }
1020     /**
1021      * Returns the an array of the users the given user is in a conversation
1022      * with who are a contact and the number of unread messages.
1023      *
1024      * @param int $userid The user id
1025      * @param int $limitfrom
1026      * @param int $limitnum
1027      * @return array
1028      */
1029     public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
1030         global $DB;
1032         $userfields = \user_picture::fields('u', array('lastaccess'));
1033         $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
1034                               FROM {message_contacts} mc
1035                         INNER JOIN {user} u
1036                                 ON (u.id = mc.contactid OR u.id = mc.userid)
1037                          LEFT JOIN {messages} m
1038                                 ON ((m.useridfrom = mc.contactid OR m.useridfrom = mc.userid) AND m.useridfrom != ?)
1039                          LEFT JOIN {message_conversation_members} mcm
1040                                 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
1041                          LEFT JOIN {message_user_actions} mua
1042                                 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1043                          LEFT JOIN {message_users_blocked} mub
1044                                 ON (mub.userid = ? AND mub.blockeduserid = u.id)
1045                              WHERE mua.id is NULL
1046                                AND mub.id is NULL
1047                                AND (mc.userid = ? OR mc.contactid = ?)
1048                                AND u.id != ?
1049                                AND u.deleted = 0
1050                           GROUP BY $userfields";
1052         return $DB->get_records_sql($unreadcountssql, [$userid, $userid, $userid, self::MESSAGE_ACTION_READ,
1053             $userid, $userid, $userid, $userid], $limitfrom, $limitnum);
1054     }
1056     /**
1057      * Returns the an array of the users the given user is in a conversation
1058      * with who are not a contact and the number of unread messages.
1059      *
1060      * @param int $userid The user id
1061      * @param int $limitfrom
1062      * @param int $limitnum
1063      * @return array
1064      */
1065     public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
1066         global $DB;
1068         $userfields = \user_picture::fields('u', array('lastaccess'));
1069         $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
1070                               FROM {user} u
1071                         INNER JOIN {messages} m
1072                                 ON m.useridfrom = u.id
1073                         INNER JOIN {message_conversation_members} mcm
1074                                 ON mcm.conversationid = m.conversationid
1075                          LEFT JOIN {message_user_actions} mua
1076                                 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1077                          LEFT JOIN {message_contacts} mc
1078                                 ON (mc.userid = ? AND mc.contactid = u.id)
1079                          LEFT JOIN {message_users_blocked} mub
1080                                 ON (mub.userid = ? AND mub.blockeduserid = u.id)
1081                              WHERE mcm.userid = ?
1082                                AND mcm.userid != m.useridfrom
1083                                AND mua.id is NULL
1084                                AND mub.id is NULL
1085                                AND mc.id is NULL
1086                                AND u.deleted = 0
1087                           GROUP BY $userfields";
1089         return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
1090             $limitfrom, $limitnum);
1091     }
1093     /**
1094      * Returns the messages to display in the message area.
1095      *
1096      * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1097      * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1098      * Followup: MDL-63915
1099      *
1100      * @param int $userid the current user
1101      * @param int $otheruserid the other user
1102      * @param int $limitfrom
1103      * @param int $limitnum
1104      * @param string $sort
1105      * @param int $timefrom the time from the message being sent
1106      * @param int $timeto the time up until the message being sent
1107      * @return array
1108      */
1109     public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
1110             $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
1112         if (!empty($timefrom)) {
1113             // Get the conversation between userid and otheruserid.
1114             $userids = [$userid, $otheruserid];
1115             if (!$conversationid = self::get_conversation_between_users($userids)) {
1116                 // This method was always used for individual conversations.
1117                 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
1118                 $conversationid = $conversation->id;
1119             }
1121             // Check the cache to see if we even need to do a DB query.
1122             $cache = \cache::make('core', 'message_time_last_message_between_users');
1123             $key = helper::get_last_message_time_created_cache_key($conversationid);
1124             $lastcreated = $cache->get($key);
1126             // The last known message time is earlier than the one being requested so we can
1127             // just return an empty result set rather than having to query the DB.
1128             if ($lastcreated && $lastcreated < $timefrom) {
1129                 return [];
1130             }
1131         }
1133         $arrmessages = array();
1134         if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
1135                                              $sort, $timefrom, $timeto)) {
1136             $arrmessages = helper::create_messages($userid, $messages);
1137         }
1139         return $arrmessages;
1140     }
1142     /**
1143      * Returns the messages for the defined conversation.
1144      *
1145      * @param  int $userid The current user.
1146      * @param  int $convid The conversation where the messages belong. Could be an object or just the id.
1147      * @param  int $limitfrom Return a subset of records, starting at this point (optional).
1148      * @param  int $limitnum Return a subset comprising this many records in total (optional, required if $limitfrom is set).
1149      * @param  string $sort The column name to order by including optionally direction.
1150      * @param  int $timefrom The time from the message being sent.
1151      * @param  int $timeto The time up until the message being sent.
1152      * @return array of messages
1153      */
1154     public static function get_conversation_messages(int $userid, int $convid, int $limitfrom = 0, int $limitnum = 0,
1155         string $sort = 'timecreated ASC', int $timefrom = 0, int $timeto = 0) : array {
1157         if (!empty($timefrom)) {
1158             // Check the cache to see if we even need to do a DB query.
1159             $cache = \cache::make('core', 'message_time_last_message_between_users');
1160             $key = helper::get_last_message_time_created_cache_key($convid);
1161             $lastcreated = $cache->get($key);
1163             // The last known message time is earlier than the one being requested so we can
1164             // just return an empty result set rather than having to query the DB.
1165             if ($lastcreated && $lastcreated < $timefrom) {
1166                 return [];
1167             }
1168         }
1170         $messages = helper::get_conversation_messages($userid, $convid, 0, $limitfrom, $limitnum, $sort, $timefrom, $timeto);
1171         return helper::format_conversation_messages($userid, $convid, $messages);
1172     }
1174     /**
1175      * Returns the most recent message between two users.
1176      *
1177      * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1178      * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1179      * Followup: MDL-63915
1180      *
1181      * @param int $userid the current user
1182      * @param int $otheruserid the other user
1183      * @return \stdClass|null
1184      */
1185     public static function get_most_recent_message($userid, $otheruserid) {
1186         // We want two messages here so we get an accurate 'blocktime' value.
1187         if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
1188             // Swap the order so we now have them in historical order.
1189             $messages = array_reverse($messages);
1190             $arrmessages = helper::create_messages($userid, $messages);
1191             return array_pop($arrmessages);
1192         }
1194         return null;
1195     }
1197     /**
1198      * Returns the most recent message in a conversation.
1199      *
1200      * @param int $convid The conversation identifier.
1201      * @param int $currentuserid The current user identifier.
1202      * @return \stdClass|null The most recent message.
1203      */
1204     public static function get_most_recent_conversation_message(int $convid, int $currentuserid = 0) {
1205         global $USER;
1207         if (empty($currentuserid)) {
1208             $currentuserid = $USER->id;
1209         }
1211         if ($messages = helper::get_conversation_messages($currentuserid, $convid, 0, 0, 1, 'timecreated DESC')) {
1212             $convmessages = helper::format_conversation_messages($currentuserid, $convid, $messages);
1213             return array_pop($convmessages['messages']);
1214         }
1216         return null;
1217     }
1219     /**
1220      * Returns the profile information for a contact for a user.
1221      *
1222      * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1223      * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1224      * Followup: MDL-63915
1225      *
1226      * @param int $userid The user id
1227      * @param int $otheruserid The id of the user whose profile we want to view.
1228      * @return \stdClass
1229      */
1230     public static function get_profile($userid, $otheruserid) {
1231         global $CFG, $PAGE;
1233         require_once($CFG->dirroot . '/user/lib.php');
1235         $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
1237         // Create the data we are going to pass to the renderable.
1238         $data = new \stdClass();
1239         $data->userid = $otheruserid;
1240         $data->fullname = fullname($user);
1241         $data->city = '';
1242         $data->country = '';
1243         $data->email = '';
1244         $data->isonline = null;
1245         // Get the user picture data - messaging has always shown these to the user.
1246         $userpicture = new \user_picture($user);
1247         $userpicture->size = 1; // Size f1.
1248         $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
1249         $userpicture->size = 0; // Size f2.
1250         $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
1252         $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
1253         if ($userfields) {
1254             if (isset($userfields['city'])) {
1255                 $data->city = $userfields['city'];
1256             }
1257             if (isset($userfields['country'])) {
1258                 $data->country = $userfields['country'];
1259             }
1260             if (isset($userfields['email'])) {
1261                 $data->email = $userfields['email'];
1262             }
1263             if (isset($userfields['lastaccess'])) {
1264                 $data->isonline = helper::is_online($userfields['lastaccess']);
1265             }
1266         }
1268         $data->isblocked = self::is_blocked($userid, $otheruserid);
1269         $data->iscontact = self::is_contact($userid, $otheruserid);
1271         return $data;
1272     }
1274     /**
1275      * Checks if a user can delete messages they have either received or sent.
1276      *
1277      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1278      *  but will still seem as if it was by the user)
1279      * @param int $conversationid The id of the conversation
1280      * @return bool Returns true if a user can delete the conversation, false otherwise.
1281      */
1282     public static function can_delete_conversation(int $userid, int $conversationid = null) : bool {
1283         global $USER;
1285         if (is_null($conversationid)) {
1286             debugging('\core_message\api::can_delete_conversation() now expects a \'conversationid\' to be passed.',
1287                 DEBUG_DEVELOPER);
1288             return false;
1289         }
1291         $systemcontext = \context_system::instance();
1293         if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1294             return true;
1295         }
1297         if (!self::is_user_in_conversation($userid, $conversationid)) {
1298             return false;
1299         }
1301         if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1302                 $USER->id == $userid) {
1303             return true;
1304         }
1306         return false;
1307     }
1309     /**
1310      * Deletes a conversation.
1311      *
1312      * This function does not verify any permissions.
1313      *
1314      * @deprecated since 3.6
1315      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1316      *  but will still seem as if it was by the user)
1317      * @param int $otheruserid The id of the other user in the conversation
1318      * @return bool
1319      */
1320     public static function delete_conversation($userid, $otheruserid) {
1321         debugging('\core_message\api::delete_conversation() is deprecated, please use ' .
1322             '\core_message\api::delete_conversation_by_id() instead.', DEBUG_DEVELOPER);
1324         $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
1326         // If there is no conversation, there is nothing to do.
1327         if (!$conversationid) {
1328             return true;
1329         }
1331         self::delete_conversation_by_id($userid, $conversationid);
1333         return true;
1334     }
1336     /**
1337      * Deletes a conversation for a specified user.
1338      *
1339      * This function does not verify any permissions.
1340      *
1341      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1342      *  but will still seem as if it was by the user)
1343      * @param int $conversationid The id of the other user in the conversation
1344      */
1345     public static function delete_conversation_by_id(int $userid, int $conversationid) {
1346         global $DB, $USER;
1348         // Get all messages belonging to this conversation that have not already been deleted by this user.
1349         $sql = "SELECT m.*
1350                  FROM {messages} m
1351            INNER JOIN {message_conversations} mc
1352                    ON m.conversationid = mc.id
1353             LEFT JOIN {message_user_actions} mua
1354                    ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1355                 WHERE mua.id is NULL
1356                   AND mc.id = ?
1357              ORDER BY m.timecreated ASC";
1358         $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
1360         // Ok, mark these as deleted.
1361         foreach ($messages as $message) {
1362             $mua = new \stdClass();
1363             $mua->userid = $userid;
1364             $mua->messageid = $message->id;
1365             $mua->action = self::MESSAGE_ACTION_DELETED;
1366             $mua->timecreated = time();
1367             $mua->id = $DB->insert_record('message_user_actions', $mua);
1369             \core\event\message_deleted::create_from_ids($userid, $USER->id,
1370                 $message->id, $mua->id)->trigger();
1371         }
1372     }
1374     /**
1375      * Returns the count of unread conversations (collection of messages from a single user) for
1376      * the given user.
1377      *
1378      * @param \stdClass $user the user who's conversations should be counted
1379      * @return int the count of the user's unread conversations
1380      */
1381     public static function count_unread_conversations($user = null) {
1382         global $USER, $DB;
1384         if (empty($user)) {
1385             $user = $USER;
1386         }
1388         $sql = "SELECT COUNT(DISTINCT(m.conversationid))
1389                   FROM {messages} m
1390             INNER JOIN {message_conversations} mc
1391                     ON m.conversationid = mc.id
1392             INNER JOIN {message_conversation_members} mcm
1393                     ON mc.id = mcm.conversationid
1394              LEFT JOIN {message_user_actions} mua
1395                     ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1396                  WHERE mcm.userid = ?
1397                    AND mcm.userid != m.useridfrom
1398                    AND mua.id is NULL";
1400         return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
1401     }
1403     /**
1404      * Checks if a user can mark all messages as read.
1405      *
1406      * @param int $userid The user id of who we want to mark the messages for
1407      * @param int $conversationid The id of the conversation
1408      * @return bool true if user is permitted, false otherwise
1409      * @since 3.6
1410      */
1411     public static function can_mark_all_messages_as_read(int $userid, int $conversationid) : bool {
1412         global $USER;
1414         $systemcontext = \context_system::instance();
1416         if (has_capability('moodle/site:readallmessages', $systemcontext)) {
1417             return true;
1418         }
1420         if (!self::is_user_in_conversation($userid, $conversationid)) {
1421             return false;
1422         }
1424         if ($USER->id == $userid) {
1425             return true;
1426         }
1428         return false;
1429     }
1431     /**
1432      * Returns the count of conversations (collection of messages from a single user) for
1433      * the given user.
1434      *
1435      * @param \stdClass $user The user who's conversations should be counted
1436      * @param int $type The conversation type
1437      * @param bool $excludefavourites Exclude favourite conversations
1438      * @return int the count of the user's unread conversations
1439      */
1440     public static function count_conversations($user, int $type = null, bool $excludefavourites = false) {
1441         global $DB;
1443         $params = [];
1444         $favouritessql = '';
1446         if ($excludefavourites) {
1447             $favouritessql = "AND m.conversationid NOT IN (
1448                                 SELECT itemid
1449                                 FROM {favourite}
1450                                 WHERE component = 'core_message'
1451                                 AND itemtype = 'message_conversations'
1452                                 AND userid = ?
1453                             )";
1454             $params[] = $user->id;
1455         }
1457         switch($type) {
1458             case null:
1459                 $params = array_merge([$user->id, self::MESSAGE_ACTION_DELETED, $user->id], $params);
1460                 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
1461                           FROM {messages} m
1462                      LEFT JOIN {message_conversations} c
1463                             ON m.conversationid = c.id
1464                      LEFT JOIN {message_user_actions} ma
1465                             ON ma.messageid = m.id
1466                      LEFT JOIN {message_conversation_members} mcm
1467                             ON m.conversationid = mcm.conversationid
1468                          WHERE mcm.userid = ?
1469                            AND (
1470                                     c.type != " . self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL . "
1471                                     OR
1472                                     (
1473                                         (ma.action IS NULL OR ma.action != ? OR ma.userid != ?)
1474                                         AND c.type = " . self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL . "
1475                                     )
1476                                 )
1477                                ${favouritessql}";
1478                 break;
1479             case self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL:
1480                 $params = array_merge([self::MESSAGE_ACTION_DELETED, $user->id, $user->id], $params);
1481                 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
1482                           FROM {messages} m
1483                      LEFT JOIN {message_conversations} c
1484                             ON m.conversationid = c.id
1485                      LEFT JOIN {message_user_actions} ma
1486                             ON ma.messageid = m.id
1487                      LEFT JOIN {message_conversation_members} mcm
1488                             ON m.conversationid = mcm.conversationid
1489                          WHERE (ma.action IS NULL OR ma.action != ? OR ma.userid != ?)
1490                            AND mcm.userid = ?
1491                            AND c.type = " . self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL . "
1492                                ${favouritessql}";
1493                 break;
1494             default:
1495                 $params = array_merge([$user->id, $type], $params);
1496                 $sql = "SELECT COUNT(m.conversationid)
1497                           FROM {message_conversation_members} m
1498                      LEFT JOIN {message_conversations} c
1499                             ON m.conversationid = c.id
1500                          WHERE m.userid = ?
1501                            AND c.type = ?
1502                                ${favouritessql}";
1504         }
1506         return $DB->count_records_sql($sql, $params);
1507     }
1509     /**
1510      * Marks all messages being sent to a user in a particular conversation.
1511      *
1512      * If $conversationdid is null then it marks all messages as read sent to $userid.
1513      *
1514      * @param int $userid
1515      * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
1516      */
1517     public static function mark_all_messages_as_read($userid, $conversationid = null) {
1518         global $DB;
1520         $messagesql = "SELECT m.*
1521                          FROM {messages} m
1522                    INNER JOIN {message_conversations} mc
1523                            ON mc.id = m.conversationid
1524                    INNER JOIN {message_conversation_members} mcm
1525                            ON mcm.conversationid = mc.id
1526                     LEFT JOIN {message_user_actions} mua
1527                            ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1528                         WHERE mua.id is NULL
1529                           AND mcm.userid = ?
1530                           AND m.useridfrom != ?";
1531         $messageparams = [];
1532         $messageparams[] = $userid;
1533         $messageparams[] = self::MESSAGE_ACTION_READ;
1534         $messageparams[] = $userid;
1535         $messageparams[] = $userid;
1536         if (!is_null($conversationid)) {
1537             $messagesql .= " AND mc.id = ?";
1538             $messageparams[] = $conversationid;
1539         }
1541         $messages = $DB->get_recordset_sql($messagesql, $messageparams);
1542         foreach ($messages as $message) {
1543             self::mark_message_as_read($userid, $message);
1544         }
1545         $messages->close();
1546     }
1548     /**
1549      * Marks all notifications being sent from one user to another user as read.
1550      *
1551      * If the from user is null then it marks all notifications as read sent to the to user.
1552      *
1553      * @param int $touserid the id of the message recipient
1554      * @param int|null $fromuserid the id of the message sender, null if all messages
1555      * @return void
1556      */
1557     public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
1558         global $DB;
1560         $notificationsql = "SELECT n.*
1561                               FROM {notifications} n
1562                              WHERE useridto = ?
1563                                AND timeread is NULL";
1564         $notificationsparams = [$touserid];
1565         if (!empty($fromuserid)) {
1566             $notificationsql .= " AND useridfrom = ?";
1567             $notificationsparams[] = $fromuserid;
1568         }
1570         $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
1571         foreach ($notifications as $notification) {
1572             self::mark_notification_as_read($notification);
1573         }
1574         $notifications->close();
1575     }
1577     /**
1578      * Marks ALL messages being sent from $fromuserid to $touserid as read.
1579      *
1580      * Can be filtered by type.
1581      *
1582      * @deprecated since 3.5
1583      * @param int $touserid the id of the message recipient
1584      * @param int $fromuserid the id of the message sender
1585      * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
1586      * @return void
1587      */
1588     public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
1589         debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
1590             '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
1591             DEBUG_DEVELOPER);
1593         $type = strtolower($type);
1595         $conversationid = null;
1596         $ignoremessages = false;
1597         if (!empty($fromuserid)) {
1598             $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
1599             if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
1600                 $ignoremessages = true;
1601             }
1602         }
1604         if (!empty($type)) {
1605             if ($type == MESSAGE_TYPE_NOTIFICATION) {
1606                 self::mark_all_notifications_as_read($touserid, $fromuserid);
1607             } else if ($type == MESSAGE_TYPE_MESSAGE) {
1608                 if (!$ignoremessages) {
1609                     self::mark_all_messages_as_read($touserid, $conversationid);
1610                 }
1611             }
1612         } else { // We want both.
1613             self::mark_all_notifications_as_read($touserid, $fromuserid);
1614             if (!$ignoremessages) {
1615                 self::mark_all_messages_as_read($touserid, $conversationid);
1616             }
1617         }
1618     }
1620     /**
1621      * Returns message preferences.
1622      *
1623      * @param array $processors
1624      * @param array $providers
1625      * @param \stdClass $user
1626      * @return \stdClass
1627      * @since 3.2
1628      */
1629     public static function get_all_message_preferences($processors, $providers, $user) {
1630         $preferences = helper::get_providers_preferences($providers, $user->id);
1631         $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
1633         // For every processors put its options on the form (need to get function from processor's lib.php).
1634         foreach ($processors as $processor) {
1635             $processor->object->load_data($preferences, $user->id);
1636         }
1638         // Load general messaging preferences.
1639         $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
1640         $preferences->mailformat = $user->mailformat;
1641         $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
1643         return $preferences;
1644     }
1646     /**
1647      * Count the number of users blocked by a user.
1648      *
1649      * @param \stdClass $user The user object
1650      * @return int the number of blocked users
1651      */
1652     public static function count_blocked_users($user = null) {
1653         global $USER, $DB;
1655         if (empty($user)) {
1656             $user = $USER;
1657         }
1659         $sql = "SELECT count(mub.id)
1660                   FROM {message_users_blocked} mub
1661                  WHERE mub.userid = :userid";
1662         return $DB->count_records_sql($sql, array('userid' => $user->id));
1663     }
1665     /**
1666      * Determines if a user is permitted to send another user a private message.
1667      * If no sender is provided then it defaults to the logged in user.
1668      *
1669      * @param \stdClass $recipient The user object.
1670      * @param \stdClass|null $sender The user object.
1671      * @return bool true if user is permitted, false otherwise.
1672      */
1673     public static function can_post_message($recipient, $sender = null) {
1674         global $USER;
1676         if (is_null($sender)) {
1677             // The message is from the logged in user, unless otherwise specified.
1678             $sender = $USER;
1679         }
1681         $systemcontext = \context_system::instance();
1682         if (!has_capability('moodle/site:sendmessage', $systemcontext, $sender)) {
1683             return false;
1684         }
1686         if (has_capability('moodle/site:readallmessages', $systemcontext, $sender->id)) {
1687             return true;
1688         }
1690         // Check if the recipient can be messaged by the sender.
1691         return (self::can_contact_user($recipient->id, $sender->id));
1692     }
1694     /**
1695      * Determines if a user is permitted to send a message to a given conversation.
1696      * If no sender is provided then it defaults to the logged in user.
1697      *
1698      * @param int $userid the id of the user on which the checks will be applied.
1699      * @param int $conversationid the id of the conversation we wish to check.
1700      * @return bool true if the user can send a message to the conversation, false otherwise.
1701      * @throws \moodle_exception
1702      */
1703     public static function can_send_message_to_conversation(int $userid, int $conversationid) : bool {
1704         global $DB;
1706         $systemcontext = \context_system::instance();
1707         if (!has_capability('moodle/site:sendmessage', $systemcontext, $userid)) {
1708             return false;
1709         }
1711         if (!self::is_user_in_conversation($userid, $conversationid)) {
1712             return false;
1713         }
1715         // User can post messages and is in the conversation, but we need to check the conversation type to
1716         // know whether or not to check the user privacy settings via can_contact_user().
1717         $conversation = $DB->get_record('message_conversations', ['id' => $conversationid], '*', MUST_EXIST);
1718         if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
1719             return true;
1720         } else if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1721             // Get the other user in the conversation.
1722             $members = self::get_conversation_members($userid, $conversationid);
1723             $otheruser = array_filter($members, function($member) use($userid) {
1724                 return $member->id != $userid;
1725             });
1726             $otheruser = reset($otheruser);
1728             return self::can_contact_user($otheruser->id, $userid);
1729         } else {
1730             throw new \moodle_exception("Invalid conversation type '$conversation->type'.");
1731         }
1732     }
1734     /**
1735      * Send a message from a user to a conversation.
1736      *
1737      * This method will create the basic eventdata and delegate to message creation to message_send.
1738      * The message_send() method is responsible for event data that is specific to each recipient.
1739      *
1740      * @param int $userid the sender id.
1741      * @param int $conversationid the conversation id.
1742      * @param string $message the message to send.
1743      * @param int $format the format of the message to send.
1744      * @return \stdClass the message created.
1745      * @throws \coding_exception
1746      * @throws \moodle_exception if the user is not permitted to send a message to the conversation.
1747      */
1748     public static function send_message_to_conversation(int $userid, int $conversationid, string $message,
1749                                                         int $format) : \stdClass {
1750         global $DB;
1752         if (!self::can_send_message_to_conversation($userid, $conversationid)) {
1753             throw new \moodle_exception("User $userid cannot send a message to conversation $conversationid");
1754         }
1756         $eventdata = new \core\message\message();
1757         $eventdata->courseid         = 1;
1758         $eventdata->component        = 'moodle';
1759         $eventdata->name             = 'instantmessage';
1760         $eventdata->userfrom         = $userid;
1761         $eventdata->convid           = $conversationid;
1763         if ($format == FORMAT_HTML) {
1764             $eventdata->fullmessagehtml  = $message;
1765             // Some message processors may revert to sending plain text even if html is supplied,
1766             // so we keep both plain and html versions if we're intending to send html.
1767             $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
1768         } else {
1769             $eventdata->fullmessage      = $message;
1770             $eventdata->fullmessagehtml  = '';
1771         }
1773         $eventdata->fullmessageformat = $format;
1774         $eventdata->smallmessage = $message; // Store the message unfiltered. Clean up on output.
1776         $eventdata->timecreated     = time();
1777         $eventdata->notification    = 0;
1778         $messageid = message_send($eventdata);
1780         $messagerecord = $DB->get_record('messages', ['id' => $messageid], 'id, useridfrom, fullmessage, timecreated');
1781         $message = (object) [
1782             'id' => $messagerecord->id,
1783             'useridfrom' => $messagerecord->useridfrom,
1784             'text' => $messagerecord->fullmessage,
1785             'timecreated' => $messagerecord->timecreated
1786         ];
1787         return $message;
1788     }
1790     /**
1791      * Get the messaging preference for a user.
1792      * If the user has not any messaging privacy preference:
1793      * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
1794      * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
1795      *
1796      * @param  int    $userid The user identifier.
1797      * @return int    The default messaging preference.
1798      */
1799     public static function get_user_privacy_messaging_preference(int $userid) : int {
1800         global $CFG, $USER;
1802         // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
1803         // otherwise, the default value will be "My contacts and anyone in my courses".
1804         if (empty($CFG->messagingallusers)) {
1805             $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
1806         } else {
1807             $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
1808         }
1809         if ($userid == $USER->id) {
1810             $user = $USER;
1811         } else {
1812             $user = $userid;
1813         }
1814         $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $user);
1816         // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
1817         // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1818         if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
1819             $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
1820         }
1822         return $privacypreference;
1823     }
1825     /**
1826      * Checks if the recipient is allowing messages from users that aren't a
1827      * contact. If not then it checks to make sure the sender is in the
1828      * recipient's contacts.
1829      *
1830      * @deprecated since 3.6
1831      * @param \stdClass $recipient The user object.
1832      * @param \stdClass|null $sender The user object.
1833      * @return bool true if $sender is blocked, false otherwise.
1834      */
1835     public static function is_user_non_contact_blocked($recipient, $sender = null) {
1836         debugging('\core_message\api::is_user_non_contact_blocked() is deprecated', DEBUG_DEVELOPER);
1838         global $USER, $CFG;
1840         if (is_null($sender)) {
1841             // The message is from the logged in user, unless otherwise specified.
1842             $sender = $USER;
1843         }
1845         $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1846         switch ($privacypreference) {
1847             case self::MESSAGE_PRIVACY_SITE:
1848                 if (!empty($CFG->messagingallusers)) {
1849                     // Users can be messaged without being contacts or members of the same course.
1850                     break;
1851                 }
1852                 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1853                 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1854             case self::MESSAGE_PRIVACY_COURSEMEMBER:
1855                 // Confirm the sender and the recipient are both members of the same course.
1856                 if (enrol_sharing_course($recipient, $sender)) {
1857                     // All good, the recipient and the sender are members of the same course.
1858                     return false;
1859                 }
1860             case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1861                 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1862                 return !self::is_contact($sender->id, $recipient->id);
1863         }
1865         return false;
1866     }
1868     /**
1869      * Checks if the recipient has specifically blocked the sending user.
1870      *
1871      * Note: This function will always return false if the sender has the
1872      * readallmessages capability at the system context level.
1873      *
1874      * @deprecated since 3.6
1875      * @param int $recipientid User ID of the recipient.
1876      * @param int $senderid User ID of the sender.
1877      * @return bool true if $sender is blocked, false otherwise.
1878      */
1879     public static function is_user_blocked($recipientid, $senderid = null) {
1880         debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1881             DEBUG_DEVELOPER);
1883         global $USER;
1885         if (is_null($senderid)) {
1886             // The message is from the logged in user, unless otherwise specified.
1887             $senderid = $USER->id;
1888         }
1890         $systemcontext = \context_system::instance();
1891         if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
1892             return false;
1893         }
1895         if (self::is_blocked($recipientid, $senderid)) {
1896             return true;
1897         }
1899         return false;
1900     }
1902     /**
1903      * Get specified message processor, validate corresponding plugin existence and
1904      * system configuration.
1905      *
1906      * @param string $name  Name of the processor.
1907      * @param bool $ready only return ready-to-use processors.
1908      * @return mixed $processor if processor present else empty array.
1909      * @since Moodle 3.2
1910      */
1911     public static function get_message_processor($name, $ready = false) {
1912         global $DB, $CFG;
1914         $processor = $DB->get_record('message_processors', array('name' => $name));
1915         if (empty($processor)) {
1916             // Processor not found, return.
1917             return array();
1918         }
1920         $processor = self::get_processed_processor_object($processor);
1921         if ($ready) {
1922             if ($processor->enabled && $processor->configured) {
1923                 return $processor;
1924             } else {
1925                 return array();
1926             }
1927         } else {
1928             return $processor;
1929         }
1930     }
1932     /**
1933      * Returns weather a given processor is enabled or not.
1934      * Note:- This doesn't check if the processor is configured or not.
1935      *
1936      * @param string $name Name of the processor
1937      * @return bool
1938      */
1939     public static function is_processor_enabled($name) {
1941         $cache = \cache::make('core', 'message_processors_enabled');
1942         $status = $cache->get($name);
1944         if ($status === false) {
1945             $processor = self::get_message_processor($name);
1946             if (!empty($processor)) {
1947                 $cache->set($name, $processor->enabled);
1948                 return $processor->enabled;
1949             } else {
1950                 return false;
1951             }
1952         }
1954         return $status;
1955     }
1957     /**
1958      * Set status of a processor.
1959      *
1960      * @param \stdClass $processor processor record.
1961      * @param 0|1 $enabled 0 or 1 to set the processor status.
1962      * @return bool
1963      * @since Moodle 3.2
1964      */
1965     public static function update_processor_status($processor, $enabled) {
1966         global $DB;
1967         $cache = \cache::make('core', 'message_processors_enabled');
1968         $cache->delete($processor->name);
1969         return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1970     }
1972     /**
1973      * Given a processor object, loads information about it's settings and configurations.
1974      * This is not a public api, instead use @see \core_message\api::get_message_processor()
1975      * or @see \get_message_processors()
1976      *
1977      * @param \stdClass $processor processor object
1978      * @return \stdClass processed processor object
1979      * @since Moodle 3.2
1980      */
1981     public static function get_processed_processor_object(\stdClass $processor) {
1982         global $CFG;
1984         $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1985         if (is_readable($processorfile)) {
1986             include_once($processorfile);
1987             $processclass = 'message_output_' . $processor->name;
1988             if (class_exists($processclass)) {
1989                 $pclass = new $processclass();
1990                 $processor->object = $pclass;
1991                 $processor->configured = 0;
1992                 if ($pclass->is_system_configured()) {
1993                     $processor->configured = 1;
1994                 }
1995                 $processor->hassettings = 0;
1996                 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1997                     $processor->hassettings = 1;
1998                 }
1999                 $processor->available = 1;
2000             } else {
2001                 print_error('errorcallingprocessor', 'message');
2002             }
2003         } else {
2004             $processor->available = 0;
2005         }
2006         return $processor;
2007     }
2009     /**
2010      * Retrieve users blocked by $user1
2011      *
2012      * @param int $userid The user id of the user whos blocked users we are returning
2013      * @return array the users blocked
2014      */
2015     public static function get_blocked_users($userid) {
2016         global $DB;
2018         $userfields = \user_picture::fields('u', array('lastaccess'));
2019         $blockeduserssql = "SELECT $userfields
2020                               FROM {message_users_blocked} mub
2021                         INNER JOIN {user} u
2022                                 ON u.id = mub.blockeduserid
2023                              WHERE u.deleted = 0
2024                                AND mub.userid = ?
2025                           GROUP BY $userfields
2026                           ORDER BY u.firstname ASC";
2027         return $DB->get_records_sql($blockeduserssql, [$userid]);
2028     }
2030     /**
2031      * Mark a single message as read.
2032      *
2033      * @param int $userid The user id who marked the message as read
2034      * @param \stdClass $message The message
2035      * @param int|null $timeread The time the message was marked as read, if null will default to time()
2036      */
2037     public static function mark_message_as_read($userid, $message, $timeread = null) {
2038         global $DB;
2040         if (is_null($timeread)) {
2041             $timeread = time();
2042         }
2044         $mua = new \stdClass();
2045         $mua->userid = $userid;
2046         $mua->messageid = $message->id;
2047         $mua->action = self::MESSAGE_ACTION_READ;
2048         $mua->timecreated = $timeread;
2049         $mua->id = $DB->insert_record('message_user_actions', $mua);
2051         // Get the context for the user who received the message.
2052         $context = \context_user::instance($userid, IGNORE_MISSING);
2053         // If the user no longer exists the context value will be false, in this case use the system context.
2054         if ($context === false) {
2055             $context = \context_system::instance();
2056         }
2058         // Trigger event for reading a message.
2059         $event = \core\event\message_viewed::create(array(
2060             'objectid' => $mua->id,
2061             'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
2062             'context' => $context,
2063             'relateduserid' => $message->useridfrom,
2064             'other' => array(
2065                 'messageid' => $message->id
2066             )
2067         ));
2068         $event->trigger();
2069     }
2071     /**
2072      * Mark a single notification as read.
2073      *
2074      * @param \stdClass $notification The notification
2075      * @param int|null $timeread The time the message was marked as read, if null will default to time()
2076      */
2077     public static function mark_notification_as_read($notification, $timeread = null) {
2078         global $DB;
2080         if (is_null($timeread)) {
2081             $timeread = time();
2082         }
2084         if (is_null($notification->timeread)) {
2085             $updatenotification = new \stdClass();
2086             $updatenotification->id = $notification->id;
2087             $updatenotification->timeread = $timeread;
2089             $DB->update_record('notifications', $updatenotification);
2091             // Trigger event for reading a notification.
2092             \core\event\notification_viewed::create_from_ids(
2093                 $notification->useridfrom,
2094                 $notification->useridto,
2095                 $notification->id
2096             )->trigger();
2097         }
2098     }
2100     /**
2101      * Checks if a user can delete a message.
2102      *
2103      * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
2104      *  but will still seem as if it was by the user)
2105      * @param int $messageid The message id
2106      * @return bool Returns true if a user can delete the message, false otherwise.
2107      */
2108     public static function can_delete_message($userid, $messageid) {
2109         global $DB, $USER;
2111         $systemcontext = \context_system::instance();
2113         $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
2115         if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
2116             return true;
2117         }
2119         if (!self::is_user_in_conversation($userid, $conversationid)) {
2120             return false;
2121         }
2123         if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
2124                 $USER->id == $userid) {
2125             return true;
2126         }
2128         return false;
2129     }
2131     /**
2132      * Deletes a message.
2133      *
2134      * This function does not verify any permissions.
2135      *
2136      * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
2137      *  but will still seem as if it was by the user)
2138      * @param int $messageid The message id
2139      * @return bool
2140      */
2141     public static function delete_message($userid, $messageid) {
2142         global $DB, $USER;
2144         if (!$DB->record_exists('messages', ['id' => $messageid])) {
2145             return false;
2146         }
2148         // Check if the user has already deleted this message.
2149         if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
2150                 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
2151             $mua = new \stdClass();
2152             $mua->userid = $userid;
2153             $mua->messageid = $messageid;
2154             $mua->action = self::MESSAGE_ACTION_DELETED;
2155             $mua->timecreated = time();
2156             $mua->id = $DB->insert_record('message_user_actions', $mua);
2158             // Trigger event for deleting a message.
2159             \core\event\message_deleted::create_from_ids($userid, $USER->id,
2160                 $messageid, $mua->id)->trigger();
2162             return true;
2163         }
2165         return false;
2166     }
2168     /**
2169      * Returns the conversation between two users.
2170      *
2171      * @param array $userids
2172      * @return int|bool The id of the conversation, false if not found
2173      */
2174     public static function get_conversation_between_users(array $userids) {
2175         global $DB;
2177         $conversations = self::get_individual_conversations_between_users([$userids]);
2178         $conversation = $conversations[0];
2180         if ($conversation) {
2181             return $conversation->id;
2182         }
2184         return false;
2185     }
2187     /**
2188      * Returns the conversations between sets of users.
2189      *
2190      * The returned array of results will be in the same order as the requested
2191      * arguments, null will be returned if there is no conversation for that user
2192      * pair.
2193      *
2194      * For example:
2195      * If we have 6 users with ids 1, 2, 3, 4, 5, 6 where only 2 conversations
2196      * exist. One between 1 and 2 and another between 5 and 6.
2197      *
2198      * Then if we call:
2199      * $conversations = get_individual_conversations_between_users([[1,2], [3,4], [5,6]]);
2200      *
2201      * The conversations array will look like:
2202      * [<conv_record>, null, <conv_record>];
2203      *
2204      * Where null is returned for the pairing of [3, 4] since no record exists.
2205      *
2206      * @param array $useridsets An array of arrays where the inner array is the set of user ids
2207      * @return stdClass[] Array of conversation records
2208      */
2209     public static function get_individual_conversations_between_users(array $useridsets) : array {
2210         global $DB;
2212         if (empty($useridsets)) {
2213             return [];
2214         }
2216         $hashes = array_map(function($userids) {
2217             return  helper::get_conversation_hash($userids);
2218         }, $useridsets);
2220         list($inorequalsql, $params) = $DB->get_in_or_equal($hashes);
2221         array_unshift($params, self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL);
2222         $where = "type = ? AND convhash ${inorequalsql}";
2223         $conversations = array_fill(0, count($hashes), null);
2224         $records = $DB->get_records_select('message_conversations', $where, $params);
2226         foreach (array_values($records) as $record) {
2227             $index = array_search($record->convhash, $hashes);
2228             if ($index !== false) {
2229                 $conversations[$index] = $record;
2230             }
2231         }
2233         return $conversations;
2234     }
2236     /**
2237      * Creates a conversation between two users.
2238      *
2239      * @deprecated since 3.6
2240      * @param array $userids
2241      * @return int The id of the conversation
2242      */
2243     public static function create_conversation_between_users(array $userids) {
2244         debugging('\core_message\api::create_conversation_between_users is deprecated, please use ' .
2245             '\core_message\api::create_conversation instead.', DEBUG_DEVELOPER);
2247         // This method was always used for individual conversations.
2248         $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
2250         return $conversation->id;
2251     }
2253     /**
2254      * Creates a conversation with selected users and messages.
2255      *
2256      * @param int $type The type of conversation
2257      * @param int[] $userids The array of users to add to the conversation
2258      * @param string|null $name The name of the conversation
2259      * @param int $enabled Determines if the conversation is created enabled or disabled
2260      * @param string|null $component Defines the Moodle component which the conversation belongs to, if any
2261      * @param string|null $itemtype Defines the type of the component
2262      * @param int|null $itemid The id of the component
2263      * @param int|null $contextid The id of the context
2264      * @return \stdClass
2265      */
2266     public static function create_conversation(int $type, array $userids, string $name = null,
2267             int $enabled = self::MESSAGE_CONVERSATION_ENABLED, string $component = null,
2268             string $itemtype = null, int $itemid = null, int $contextid = null) {
2270         global $DB;
2272         $validtypes = [
2273             self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2274             self::MESSAGE_CONVERSATION_TYPE_GROUP
2275         ];
2277         if (!in_array($type, $validtypes)) {
2278             throw new \moodle_exception('An invalid conversation type was specified.');
2279         }
2281         // Sanity check.
2282         if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
2283             if (count($userids) > 2) {
2284                 throw new \moodle_exception('An individual conversation can not have more than two users.');
2285             }
2286         }
2288         $conversation = new \stdClass();
2289         $conversation->type = $type;
2290         $conversation->name = $name;
2291         $conversation->convhash = null;
2292         if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
2293             $conversation->convhash = helper::get_conversation_hash($userids);
2294         }
2295         $conversation->component = $component;
2296         $conversation->itemtype = $itemtype;
2297         $conversation->itemid = $itemid;
2298         $conversation->contextid = $contextid;
2299         $conversation->enabled = $enabled;
2300         $conversation->timecreated = time();
2301         $conversation->timemodified = $conversation->timecreated;
2302         $conversation->id = $DB->insert_record('message_conversations', $conversation);
2304         // Add users to this conversation.
2305         $arrmembers = [];
2306         foreach ($userids as $userid) {
2307             $member = new \stdClass();
2308             $member->conversationid = $conversation->id;
2309             $member->userid = $userid;
2310             $member->timecreated = time();
2311             $member->id = $DB->insert_record('message_conversation_members', $member);
2313             $arrmembers[] = $member;
2314         }
2316         $conversation->members = $arrmembers;
2318         return $conversation;
2319     }
2321     /**
2322      * Checks if a user can create a group conversation.
2323      *
2324      * @param int $userid The id of the user attempting to create the conversation
2325      * @param \context $context The context they are creating the conversation from, most likely course context
2326      * @return bool
2327      */
2328     public static function can_create_group_conversation(int $userid, \context $context) : bool {
2329         global $CFG;
2331         // If we can't message at all, then we can't create a conversation.
2332         if (empty($CFG->messaging)) {
2333             return false;
2334         }
2336         // We need to check they have the capability to create the conversation.
2337         return has_capability('moodle/course:creategroupconversations', $context, $userid);
2338     }
2340     /**
2341      * Checks if a user can create a contact request.
2342      *
2343      * @param int $userid The id of the user who is creating the contact request
2344      * @param int $requesteduserid The id of the user being requested
2345      * @return bool
2346      */
2347     public static function can_create_contact(int $userid, int $requesteduserid) : bool {
2348         global $CFG;
2350         // If we can't message at all, then we can't create a contact.
2351         if (empty($CFG->messaging)) {
2352             return false;
2353         }
2355         // If we can message anyone on the site then we can create a contact.
2356         if ($CFG->messagingallusers) {
2357             return true;
2358         }
2360         // We need to check if they are in the same course.
2361         return enrol_sharing_course($userid, $requesteduserid);
2362     }
2364     /**
2365      * Handles creating a contact request.
2366      *
2367      * @param int $userid The id of the user who is creating the contact request
2368      * @param int $requesteduserid The id of the user being requested
2369      * @return \stdClass the request
2370      */
2371     public static function create_contact_request(int $userid, int $requesteduserid) : \stdClass {
2372         global $DB;
2374         $request = new \stdClass();
2375         $request->userid = $userid;
2376         $request->requesteduserid = $requesteduserid;
2377         $request->timecreated = time();
2379         $request->id = $DB->insert_record('message_contact_requests', $request);
2381         return $request;
2382     }
2385     /**
2386      * Handles confirming a contact request.
2387      *
2388      * @param int $userid The id of the user who created the contact request
2389      * @param int $requesteduserid The id of the user confirming the request
2390      */
2391     public static function confirm_contact_request(int $userid, int $requesteduserid) {
2392         global $DB;
2394         if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2395                 'requesteduserid' => $requesteduserid])) {
2396             self::add_contact($userid, $requesteduserid);
2398             $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2399         }
2400     }
2402     /**
2403      * Handles declining a contact request.
2404      *
2405      * @param int $userid The id of the user who created the contact request
2406      * @param int $requesteduserid The id of the user declining the request
2407      */
2408     public static function decline_contact_request(int $userid, int $requesteduserid) {
2409         global $DB;
2411         if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2412                 'requesteduserid' => $requesteduserid])) {
2413             $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2414         }
2415     }
2417     /**
2418      * Handles returning the contact requests for a user.
2419      *
2420      * This also includes the user data necessary to display information
2421      * about the user.
2422      *
2423      * It will not include blocked users.
2424      *
2425      * @param int $userid
2426      * @param int $limitfrom
2427      * @param int $limitnum
2428      * @return array The list of contact requests
2429      */
2430     public static function get_contact_requests(int $userid, int $limitfrom = 0, int $limitnum = 0) : array {
2431         global $DB;
2433         $sql = "SELECT mcr.userid
2434                   FROM {message_contact_requests} mcr
2435              LEFT JOIN {message_users_blocked} mub
2436                     ON (mub.userid = ? AND mub.blockeduserid = mcr.userid)
2437                  WHERE mcr.requesteduserid = ?
2438                    AND mub.id is NULL
2439               ORDER BY mcr.timecreated ASC";
2440         if ($contactrequests = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
2441             $userids = array_keys($contactrequests);
2442             return helper::get_member_info($userid, $userids);
2443         }
2445         return [];
2446     }
2448     /**
2449      * Count how many contact requests the user has received.
2450      *
2451      * @param \stdClass $user The user to fetch contact requests for
2452      * @return int The count
2453      */
2454     public static function count_received_contact_requests(\stdClass $user) : int {
2455         global $DB;
2456         return $DB->count_records('message_contact_requests', ['requesteduserid' => $user->id]);
2457     }
2459     /**
2460      * Handles adding a contact.
2461      *
2462      * @param int $userid The id of the user who requested to be a contact
2463      * @param int $contactid The id of the contact
2464      */
2465     public static function add_contact(int $userid, int $contactid) {
2466         global $DB;
2468         $messagecontact = new \stdClass();
2469         $messagecontact->userid = $userid;
2470         $messagecontact->contactid = $contactid;
2471         $messagecontact->timecreated = time();
2472         $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
2474         $eventparams = [
2475             'objectid' => $messagecontact->id,
2476             'userid' => $userid,
2477             'relateduserid' => $contactid,
2478             'context' => \context_user::instance($userid)
2479         ];
2480         $event = \core\event\message_contact_added::create($eventparams);
2481         $event->add_record_snapshot('message_contacts', $messagecontact);
2482         $event->trigger();
2483     }
2485     /**
2486      * Handles removing a contact.
2487      *
2488      * @param int $userid The id of the user who is removing a user as a contact
2489      * @param int $contactid The id of the user to be removed as a contact
2490      */
2491     public static function remove_contact(int $userid, int $contactid) {
2492         global $DB;
2494         if ($contact = self::get_contact($userid, $contactid)) {
2495             $DB->delete_records('message_contacts', ['id' => $contact->id]);
2497             $event = \core\event\message_contact_removed::create(array(
2498                 'objectid' => $contact->id,
2499                 'userid' => $userid,
2500                 'relateduserid' => $contactid,
2501                 'context' => \context_user::instance($userid)
2502             ));
2503             $event->add_record_snapshot('message_contacts', $contact);
2504             $event->trigger();
2505         }
2506     }
2508     /**
2509      * Handles blocking a user.
2510      *
2511      * @param int $userid The id of the user who is blocking
2512      * @param int $usertoblockid The id of the user being blocked
2513      */
2514     public static function block_user(int $userid, int $usertoblockid) {
2515         global $DB;
2517         $blocked = new \stdClass();
2518         $blocked->userid = $userid;
2519         $blocked->blockeduserid = $usertoblockid;
2520         $blocked->timecreated = time();
2521         $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
2523         // Trigger event for blocking a contact.
2524         $event = \core\event\message_user_blocked::create(array(
2525             'objectid' => $blocked->id,
2526             'userid' => $userid,
2527             'relateduserid' => $usertoblockid,
2528             'context' => \context_user::instance($userid)
2529         ));
2530         $event->add_record_snapshot('message_users_blocked', $blocked);
2531         $event->trigger();
2532     }
2534     /**
2535      * Handles unblocking a user.
2536      *
2537      * @param int $userid The id of the user who is unblocking
2538      * @param int $usertounblockid The id of the user being unblocked
2539      */
2540     public static function unblock_user(int $userid, int $usertounblockid) {
2541         global $DB;
2543         if ($blockeduser = $DB->get_record('message_users_blocked',
2544                 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
2545             $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
2547             // Trigger event for unblocking a contact.
2548             $event = \core\event\message_user_unblocked::create(array(
2549                 'objectid' => $blockeduser->id,
2550                 'userid' => $userid,
2551                 'relateduserid' => $usertounblockid,
2552                 'context' => \context_user::instance($userid)
2553             ));
2554             $event->add_record_snapshot('message_users_blocked', $blockeduser);
2555             $event->trigger();
2556         }
2557     }
2559     /**
2560      * Checks if users are already contacts.
2561      *
2562      * @param int $userid The id of one of the users
2563      * @param int $contactid The id of the other user
2564      * @return bool Returns true if they are a contact, false otherwise
2565      */
2566     public static function is_contact(int $userid, int $contactid) : bool {
2567         global $DB;
2569         $sql = "SELECT id
2570                   FROM {message_contacts} mc
2571                  WHERE (mc.userid = ? AND mc.contactid = ?)
2572                     OR (mc.userid = ? AND mc.contactid = ?)";
2573         return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
2574     }
2576     /**
2577      * Returns the row in the database table message_contacts that represents the contact between two people.
2578      *
2579      * @param int $userid The id of one of the users
2580      * @param int $contactid The id of the other user
2581      * @return mixed A fieldset object containing the record, false otherwise
2582      */
2583     public static function get_contact(int $userid, int $contactid) {
2584         global $DB;
2586         $sql = "SELECT mc.*
2587                   FROM {message_contacts} mc
2588                  WHERE (mc.userid = ? AND mc.contactid = ?)
2589                     OR (mc.userid = ? AND mc.contactid = ?)";
2590         return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
2591     }
2593     /**
2594      * Checks if a user is already blocked.
2595      *
2596      * @param int $userid
2597      * @param int $blockeduserid
2598      * @return bool Returns true if they are a blocked, false otherwise
2599      */
2600     public static function is_blocked(int $userid, int $blockeduserid) : bool {
2601         global $DB;
2603         return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
2604     }
2606     /**
2607      * Get contact requests between users.
2608      *
2609      * @param int $userid The id of the user who is creating the contact request
2610      * @param int $requesteduserid The id of the user being requested
2611      * @return \stdClass[]
2612      */
2613     public static function get_contact_requests_between_users(int $userid, int $requesteduserid) : array {
2614         global $DB;
2616         $sql = "SELECT *
2617                   FROM {message_contact_requests} mcr
2618                  WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
2619                     OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
2620         return $DB->get_records_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
2621     }
2623     /**
2624      * Checks if a contact request already exists between users.
2625      *
2626      * @param int $userid The id of the user who is creating the contact request
2627      * @param int $requesteduserid The id of the user being requested
2628      * @return bool Returns true if a contact request exists, false otherwise
2629      */
2630     public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
2631         global $DB;
2633         $sql = "SELECT id
2634                   FROM {message_contact_requests} mcr
2635                  WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
2636                     OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
2637         return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
2638     }
2640     /**
2641      * Checks if a user is already in a conversation.
2642      *
2643      * @param int $userid The id of the user we want to check if they are in a group
2644      * @param int $conversationid The id of the conversation
2645      * @return bool Returns true if a contact request exists, false otherwise
2646      */
2647     public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
2648         global $DB;
2650         return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
2651             'userid' => $userid]);
2652     }
2654     /**
2655      * Checks if the sender can message the recipient.
2656      *
2657      * @param int $recipientid
2658      * @param int $senderid
2659      * @return bool true if recipient hasn't blocked sender and sender can contact to recipient, false otherwise.
2660      */
2661     protected static function can_contact_user(int $recipientid, int $senderid) : bool {
2662         if (has_capability('moodle/site:messageanyuser', \context_system::instance(), $senderid)) {
2663             // The sender has the ability to contact any user across the entire site.
2664             return true;
2665         }
2667         // The initial value of $cancontact is null to indicate that a value has not been determined.
2668         $cancontact = null;
2670         if (self::is_blocked($recipientid, $senderid)) {
2671             // The recipient has specifically blocked this sender.
2672             $cancontact = false;
2673         }
2675         $sharedcourses = null;
2676         if (null === $cancontact) {
2677             // There are three user preference options:
2678             // - Site: Allow anyone not explicitly blocked to contact me;
2679             // - Course members: Allow anyone I am in a course with to contact me; and
2680             // - Contacts: Only allow my contacts to contact me.
2681             //
2682             // The Site option is only possible when the messagingallusers site setting is also enabled.
2684             $privacypreference = self::get_user_privacy_messaging_preference($recipientid);
2685             if (self::MESSAGE_PRIVACY_SITE === $privacypreference) {
2686                 // The user preference is to allow any user to contact them.
2687                 // No need to check anything else.
2688                 $cancontact = true;
2689             } else {
2690                 // This user only allows their own contacts, and possibly course peers, to contact them.
2691                 // If the users are contacts then we can avoid the more expensive shared courses check.
2692                 $cancontact = self::is_contact($senderid, $recipientid);
2694                 if (!$cancontact && self::MESSAGE_PRIVACY_COURSEMEMBER === $privacypreference) {
2695                     // The users are not contacts and the user allows course member messaging.
2696                     // Check whether these two users share any course together.
2697                     $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
2698                     $cancontact = (!empty($sharedcourses));
2699                 }
2700             }
2701         }
2703         if (false === $cancontact) {
2704             // At the moment the users cannot contact one another.
2705             // Check whether the messageanyuser capability applies in any of the shared courses.
2706             // This is intended to allow teachers to message students regardless of message settings.
2708             // Note: You cannot use empty($sharedcourses) here because this may be an empty array.
2709             if (null === $sharedcourses) {
2710                 $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
2711             }
2713             foreach ($sharedcourses as $course) {
2714                 // Note: enrol_get_shared_courses will preload any shared context.
2715                 if (has_capability('moodle/site:messageanyuser', \context_course::instance($course->id), $senderid)) {
2716                     $cancontact = true;
2717                     break;
2718                 }
2719             }
2720         }
2722         return $cancontact;
2723     }
2725     /**
2726      * Add some new members to an existing conversation.
2727      *
2728      * @param array $userids User ids array to add as members.
2729      * @param int $convid The conversation id. Must exists.
2730      * @throws \dml_missing_record_exception If convid conversation doesn't exist
2731      * @throws \dml_exception If there is a database error
2732      * @throws \moodle_exception If trying to add a member(s) to a non-group conversation
2733      */
2734     public static function add_members_to_conversation(array $userids, int $convid) {
2735         global $DB;
2737         $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2739         // We can only add members to a group conversation.
2740         if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2741             throw new \moodle_exception('You can not add members to a non-group conversation.');
2742         }
2744         // Be sure we are not trying to add a non existing user to the conversation. Work only with existing users.
2745         list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2746         $existingusers = $DB->get_fieldset_select('user', 'id', "id $useridcondition", $params);
2748         // Be sure we are not adding a user is already member of the conversation. Take all the members.
2749         $memberuserids = array_values($DB->get_records_menu(
2750             'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
2751         );
2753         // Work with existing new members.
2754         $members = array();
2755         $newuserids = array_diff($existingusers, $memberuserids);
2756         foreach ($newuserids as $userid) {
2757             $member = new \stdClass();
2758             $member->conversationid = $convid;
2759             $member->userid = $userid;
2760             $member->timecreated = time();
2761             $members[] = $member;
2762         }
2764         $DB->insert_records('message_conversation_members', $members);
2765     }
2767     /**
2768      * Remove some members from an existing conversation.
2769      *
2770      * @param array $userids The user ids to remove from conversation members.
2771      * @param int $convid The conversation id. Must exists.
2772      * @throws \dml_exception
2773      * @throws \moodle_exception If trying to remove a member(s) from a non-group conversation
2774      */
2775     public static function remove_members_from_conversation(array $userids, int $convid) {
2776         global $DB;
2778         $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2780         if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2781             throw new \moodle_exception('You can not remove members from a non-group conversation.');
2782         }
2784         list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2785         $params['convid'] = $convid;
2787         $DB->delete_records_select('message_conversation_members',
2788             "conversationid = :convid AND userid $useridcondition", $params);
2789     }
2791     /**
2792      * Count conversation members.
2793      *
2794      * @param int $convid The conversation id.
2795      * @return int Number of conversation members.
2796      * @throws \dml_exception
2797      */
2798     public static function count_conversation_members(int $convid) : int {
2799         global $DB;
2801         return $DB->count_records('message_conversation_members', ['conversationid' => $convid]);
2802     }
2804     /**
2805      * Checks whether or not a conversation area is enabled.
2806      *
2807      * @param string $component Defines the Moodle component which the area was added to.
2808      * @param string $itemtype Defines the type of the component.
2809      * @param int $itemid The id of the component.
2810      * @param int $contextid The id of the context.
2811      * @return bool Returns if a conversation area exists and is enabled, false otherwise
2812      */
2813     public static function is_conversation_area_enabled(string $component, string $itemtype, int $itemid, int $contextid) : bool {
2814         global $DB;
2816         return $DB->record_exists('message_conversations',
2817             [
2818                 'itemid' => $itemid,
2819                 'contextid' => $contextid,
2820                 'component' => $component,
2821                 'itemtype' => $itemtype,
2822                 'enabled' => self::MESSAGE_CONVERSATION_ENABLED
2823             ]
2824         );
2825     }
2827     /**
2828      * Get conversation by area.
2829      *
2830      * @param string $component Defines the Moodle component which the area was added to.
2831      * @param string $itemtype Defines the type of the component.
2832      * @param int $itemid The id of the component.
2833      * @param int $contextid The id of the context.
2834      * @return \stdClass
2835      */
2836     public static function get_conversation_by_area(string $component, string $itemtype, int $itemid, int $contextid) {
2837         global $DB;
2839         return $DB->get_record('message_conversations',
2840             [
2841                 'itemid' => $itemid,
2842                 'contextid' => $contextid,
2843                 'component' => $component,
2844                 'itemtype'  => $itemtype
2845             ]
2846         );
2847     }
2849     /**
2850      * Enable a conversation.
2851      *
2852      * @param int $conversationid The id of the conversation.
2853      * @return void
2854      */
2855     public static function enable_conversation(int $conversationid) {
2856         global $DB;
2858         $conversation = new \stdClass();
2859         $conversation->id = $conversationid;
2860         $conversation->enabled = self::MESSAGE_CONVERSATION_ENABLED;
2861         $conversation->timemodified = time();
2862         $DB->update_record('message_conversations', $conversation);
2863     }
2865     /**
2866      * Disable a conversation.
2867      *
2868      * @param int $conversationid The id of the conversation.
2869      * @return void
2870      */
2871     public static function disable_conversation(int $conversationid) {
2872         global $DB;
2874         $conversation = new \stdClass();
2875         $conversation->id = $conversationid;
2876         $conversation->enabled = self::MESSAGE_CONVERSATION_DISABLED;
2877         $conversation->timemodified = time();
2878         $DB->update_record('message_conversations', $conversation);
2879     }
2881     /**
2882      * Update the name of a conversation.
2883      *
2884      * @param int $conversationid The id of a conversation.
2885      * @param string $name The main name of the area
2886      * @return void
2887      */
2888     public static function update_conversation_name(int $conversationid, string $name) {
2889         global $DB;
2891         if ($conversation = $DB->get_record('message_conversations', array('id' => $conversationid))) {
2892             if ($name <> $conversation->name) {
2893                 $conversation->name = $name;
2894                 $conversation->timemodified = time();
2895                 $DB->update_record('message_conversations', $conversation);
2896             }
2897         }
2898     }
2900     /**
2901      * Returns a list of conversation members.
2902      *
2903      * @param int $userid The user we are returning the conversation members for, used by helper::get_member_info.
2904      * @param int $conversationid The id of the conversation
2905      * @param bool $includecontactrequests Do we want to include contact requests with this data?
2906      * @param bool $includeprivacyinfo Do we want to include privacy requests with this data?
2907      * @param int $limitfrom
2908      * @param int $limitnum
2909      * @return array
2910      */
2911     public static function get_conversation_members(int $userid, int $conversationid, bool $includecontactrequests = false,
2912                                                     bool $includeprivacyinfo = false, int $limitfrom = 0,
2913                                                     int $limitnum = 0) : array {
2914         global $DB;
2916         if ($members = $DB->get_records('message_conversation_members', ['conversationid' => $conversationid],
2917                 'timecreated ASC, id ASC', 'userid', $limitfrom, $limitnum)) {
2918             $userids = array_keys($members);
2919             $members = helper::get_member_info($userid, $userids, $includecontactrequests, $includeprivacyinfo);
2921             return $members;
2922         }
2924         return [];
2925     }
2927     /**
2928      * Get the unread counts for all conversations for the user, sorted by type, and including favourites.
2929      *
2930      * @param int $userid the id of the user whose conversations we'll check.
2931      * @return array the unread counts for each conversation, indexed by type.
2932      */
2933     public static function get_unread_conversation_counts(int $userid) : array {
2934         global $DB;
2936         // Get all conversations the user is in, and check unread.
2937         $unreadcountssql = 'SELECT conv.id, conv.type, indcounts.unreadcount
2938                               FROM {message_conversations} conv
2939                         INNER JOIN (
2940                                       SELECT m.conversationid, count(m.id) as unreadcount
2941                                         FROM {messages} m
2942                                   INNER JOIN {message_conversations} mc
2943                                           ON mc.id = m.conversationid
2944                                   INNER JOIN {message_conversation_members} mcm
2945                                           ON m.conversationid = mcm.conversationid
2946                                    LEFT JOIN {message_user_actions} mua
2947                                           ON (mua.messageid = m.id AND mua.userid = ? AND
2948                                              (mua.action = ? OR mua.action = ?))
2949                                        WHERE mcm.userid = ?
2950                                          AND m.useridfrom != ?
2951                                          AND mua.id is NULL
2952                                     GROUP BY m.conversationid
2953                                    ) indcounts
2954                                 ON indcounts.conversationid = conv.id
2955                              WHERE conv.enabled = 1';
2957         $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
2958             $userid, $userid]);
2960         // Get favourites, so we can track these separately.
2961         $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
2962         $favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
2963         $favouriteconvids = array_flip(array_column($favouriteconversations, 'itemid'));
2965         // Assemble the return array.
2966         $counts = ['favourites' => 0, 'types' => [
2967             self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL => 0,
2968             self::MESSAGE_CONVERSATION_TYPE_GROUP => 0
2969         ]];
2970         foreach ($unreadcounts as $convid => $info) {
2971             $counts['types'][$info->type]++;
2972             if (isset($favouriteconvids[$convid])) {
2973                 $counts['favourites']++;
2974             }
2975         }
2977         return $counts;
2978     }