MDL-63968 message: Correct use of get_in_or_equal
[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 new group messaging UI is in place and 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 new group messaging UI is in place and 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         $params = array('search' => '%' . $search . '%', 'userid1' => $userid, 'userid2' => $userid, 'userid3' => $userid);
223         // Ok, let's search for contacts first.
224         $contacts = array();
225         $sql = "SELECT $ufields, mub.id as isuserblocked
226                 FROM {user} u
227                 JOIN {message_contacts} mc
228                   ON (u.id = mc.contactid AND mc.userid = :userid1) OR (u.id = mc.userid AND mc.contactid = :userid2)
229            LEFT JOIN {message_users_blocked} mub
230                   ON (mub.userid = :userid3 AND mub.blockeduserid = u.id)
231                WHERE u.deleted = 0
232                  AND u.confirmed = 1
233                  AND " . $DB->sql_like($fullname, ':search', false) . "
234                  AND u.id $exclude
235             ORDER BY " . $DB->sql_fullname();
237         if ($users = $DB->get_records_sql($sql, $params + $excludeparams, 0, $limitnum)) {
238             foreach ($users as $user) {
239                 $user->blocked = $user->isuserblocked ? 1 : 0;
240                 $contacts[] = helper::create_contact($user);
241             }
242         }
244         // Now, let's get the courses.
245         // Make sure to limit searches to enrolled courses.
246         $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
247         $courses = array();
248         // Really we want the user to be able to view the participants if they have the capability
249         // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
250         // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
251         // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
252         if ($arrcourses = \core_course_category::search_courses(array('search' => $search), array('limit' => $limitnum),
253                 array('moodle/course:viewparticipants'))) {
254             foreach ($arrcourses as $course) {
255                 if (isset($enrolledcourses[$course->id])) {
256                     $data = new \stdClass();
257                     $data->id = $course->id;
258                     $data->shortname = $course->shortname;
259                     $data->fullname = $course->fullname;
260                     $courses[] = $data;
261                 }
262             }
263         }
265         // Let's get those non-contacts.
266         $noncontacts = array();
267         if ($CFG->messagingallusers) {
268             // In case $CFG->messagingallusers is enabled, search for all users site-wide but are not user's contact.
269             $sql = "SELECT $ufields
270                       FROM {user} u
271                  LEFT JOIN {message_users_blocked} mub
272                         ON (mub.userid = :userid1 AND mub.blockeduserid = u.id)
273                      WHERE u.deleted = 0
274                        AND u.confirmed = 1
275                        AND " . $DB->sql_like($fullname, ':search', false) . "
276                        AND u.id $exclude
277                        AND NOT EXISTS (SELECT mc.id
278                                          FROM {message_contacts} mc
279                                         WHERE (mc.userid = u.id AND mc.contactid = :userid2)
280                                            OR (mc.userid = :userid3 AND mc.contactid = u.id))
281                   ORDER BY " . $DB->sql_fullname();
282         } else {
283             // In case $CFG->messagingallusers is disabled, search for users you have a conversation with.
284             // Messaging setting could change, so could exist an old conversation with users you cannot message anymore.
285             $sql = "SELECT $ufields, mub.id as isuserblocked
286                       FROM {user} u
287                  LEFT JOIN {message_users_blocked} mub
288                         ON (mub.userid = :userid1 AND mub.blockeduserid = u.id)
289                 INNER JOIN {message_conversation_members} cm
290                         ON u.id = cm.userid
291                 INNER JOIN {message_conversation_members} cm2
292                         ON cm.conversationid = cm2.conversationid AND cm2.userid = :userid
293                      WHERE u.deleted = 0
294                        AND u.confirmed = 1
295                        AND " . $DB->sql_like($fullname, ':search', false) . "
296                        AND u.id $exclude
297                        AND NOT EXISTS (SELECT mc.id
298                                          FROM {message_contacts} mc
299                                         WHERE (mc.userid = u.id AND mc.contactid = :userid2)
300                                            OR (mc.userid = :userid3 AND mc.contactid = u.id))
301                   ORDER BY " . $DB->sql_fullname();
302             $params['userid'] = $userid;
303         }
304         if ($users = $DB->get_records_sql($sql,  $params + $excludeparams, 0, $limitnum)) {
305             foreach ($users as $user) {
306                 $noncontacts[] = helper::create_contact($user);
307             }
308         }
310         return array($contacts, $courses, $noncontacts);
311     }
313     /**
314      * Handles searching for user.
315      *
316      * @param int $userid The user id doing the searching
317      * @param string $search The string the user is searching
318      * @param int $limitfrom
319      * @param int $limitnum
320      * @return array
321      */
322     public static function message_search_users(int $userid, string $search, int $limitfrom = 0, int $limitnum = 1000) : array {
323         global $CFG, $DB;
325         // Used to search for contacts.
326         $fullname = $DB->sql_fullname();
328         // Users not to include.
329         $excludeusers = array($userid, $CFG->siteguest);
330         list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
332         $params = array('search' => '%' . $search . '%', 'userid1' => $userid, 'userid2' => $userid);
334         // Ok, let's search for contacts first.
335         $sql = "SELECT u.id
336                   FROM {user} u
337                   JOIN {message_contacts} mc
338                     ON (u.id = mc.contactid AND mc.userid = :userid1) OR (u.id = mc.userid AND mc.contactid = :userid2)
339                  WHERE u.deleted = 0
340                    AND u.confirmed = 1
341                    AND " . $DB->sql_like($fullname, ':search', false) . "
342                    AND u.id $exclude
343               ORDER BY " . $DB->sql_fullname();
344         $foundusers = $DB->get_records_sql_menu($sql, $params + $excludeparams, $limitfrom, $limitnum);
346         $orderedcontacs = array();
347         if (!empty($foundusers)) {
348             $contacts = helper::get_member_info($userid, array_keys($foundusers));
349             // The get_member_info returns an associative array, so is not ordered in the same way.
350             // We need to reorder it again based on query's result.
351             foreach ($foundusers as $key => $value) {
352                 $contact = $contacts[$key];
353                 $contact->conversations = self::get_conversations_between_users($userid, $key, 0, 1000);
354                 $orderedcontacs[] = $contact;
355             }
356         }
358         // Let's get those non-contacts.
359         if ($CFG->messagingallusers) {
360             // In case $CFG->messagingallusers is enabled, search for all users site-wide but are not user's contact.
361             $sql = "SELECT u.id
362                       FROM {user} u
363                      WHERE u.deleted = 0
364                        AND u.confirmed = 1
365                        AND " . $DB->sql_like($fullname, ':search', false) . "
366                        AND u.id $exclude
367                        AND NOT EXISTS (SELECT mc.id
368                                          FROM {message_contacts} mc
369                                         WHERE (mc.userid = u.id AND mc.contactid = :userid1)
370                                            OR (mc.userid = :userid2 AND mc.contactid = u.id))
371                   ORDER BY " . $DB->sql_fullname();
372         } else {
373             // In case $CFG->messagingallusers is disabled, search for users you have a conversation with.
374             // Messaging setting could change, so could exist an old conversation with users you cannot message anymore.
375             $sql = "SELECT u.id
376                       FROM {user} u
377                 INNER JOIN {message_conversation_members} cm
378                         ON u.id = cm.userid
379                 INNER JOIN {message_conversation_members} cm2
380                         ON cm.conversationid = cm2.conversationid AND cm2.userid = :userid
381                      WHERE u.deleted = 0
382                        AND u.confirmed = 1
383                        AND " . $DB->sql_like($fullname, ':search', false) . "
384                        AND u.id $exclude
385                        AND NOT EXISTS (SELECT mc.id
386                                          FROM {message_contacts} mc
387                                         WHERE (mc.userid = u.id AND mc.contactid = :userid1)
388                                            OR (mc.userid = :userid2 AND mc.contactid = u.id))
389                   ORDER BY " . $DB->sql_fullname();
390             $params['userid'] = $userid;
391         }
392         $foundusers = $DB->get_records_sql_menu($sql, $params + $excludeparams, $limitfrom, $limitnum);
394         $orderednoncontacs = array();
395         if (!empty($foundusers)) {
396             $noncontacts = helper::get_member_info($userid, array_keys($foundusers));
397             // The get_member_info returns an associative array, so is not ordered in the same way.
398             // We need to reorder it again based on query's result.
399             foreach ($foundusers as $key => $value) {
400                 $contact = $noncontacts[$key];
401                 $contact->conversations = self::get_conversations_between_users($userid, $key, 0, 1000);
402                 $orderednoncontacs[] = $contact;
403             }
404         }
406         return array($orderedcontacs, $orderednoncontacs);
407     }
409     /**
410      * Gets extra fields, like image url and subname for any conversations linked to components.
411      *
412      * The subname is like a subtitle for the conversation, to compliment it's name.
413      * The imageurl is the location of the image for the conversation, as might be seen on a listing of conversations for a user.
414      *
415      * @param array $conversations a list of conversations records.
416      * @return array the array of subnames, index by conversation id.
417      * @throws \coding_exception
418      * @throws \dml_exception
419      */
420     protected static function get_linked_conversation_extra_fields(array $conversations) : array {
421         global $DB;
423         $linkedconversations = [];
424         foreach ($conversations as $conversation) {
425             if (!is_null($conversation->component) && !is_null($conversation->itemtype)) {
426                 $linkedconversations[$conversation->component][$conversation->itemtype][$conversation->id]
427                     = $conversation->itemid;
428             }
429         }
430         if (empty($linkedconversations)) {
431             return [];
432         }
434         // TODO: MDL-63814: Working out the subname for linked conversations should be done in a generic way.
435         // Get the itemid, but only for course group linked conversation for now.
436         $extrafields = [];
437         if (!empty($linkeditems = $linkedconversations['core_group']['groups'])) { // Format: [conversationid => itemid].
438             // Get the name of the course to which the group belongs.
439             list ($groupidsql, $groupidparams) = $DB->get_in_or_equal(array_values($linkeditems), SQL_PARAMS_NAMED, 'groupid');
440             $sql = "SELECT g.*, c.shortname as courseshortname
441                       FROM {groups} g
442                       JOIN {course} c
443                         ON g.courseid = c.id
444                      WHERE g.id $groupidsql";
445             $courseinfo = $DB->get_records_sql($sql, $groupidparams);
446             foreach ($linkeditems as $convid => $groupid) {
447                 if (array_key_exists($groupid, $courseinfo)) {
448                     $group = $courseinfo[$groupid];
449                     // Subname.
450                     $extrafields[$convid]['subname'] = format_string($courseinfo[$groupid]->courseshortname);
452                     // Imageurl.
453                     $extrafields[$convid]['imageurl'] = '';
454                     if ($url = get_group_picture_url($group, $group->courseid, true)) {
455                         $extrafields[$convid]['imageurl'] = $url->out(false);
456                     }
457                 }
458             }
459         }
460         return $extrafields;
461     }
464     /**
465      * Returns the contacts and their conversation to display in the contacts area.
466      *
467      * ** WARNING **
468      * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
469      * to retrieve too much information in a single call will cause performance problems.
470      * ** WARNING **
471      *
472      * This function has specifically been altered to break each of the data sets it
473      * requires into separate database calls. This is to avoid the performance problems
474      * observed when attempting to join large data sets (e.g. the message tables and
475      * the user table).
476      *
477      * While it is possible to gather the data in a single query, and it may even be
478      * more efficient with a correctly tuned database, we have opted to trade off some of
479      * the benefits of a single query in order to ensure this function will work on
480      * most databases with default tunings and with large data sets.
481      *
482      * @param int $userid The user id
483      * @param int $limitfrom
484      * @param int $limitnum
485      * @param int $type the type of the conversation, if you wish to filter to a certain type (see api constants).
486      * @param bool $favourites whether to include NO favourites (false) or ONLY favourites (true), or null to ignore this setting.
487      * @return array the array of conversations
488      * @throws \moodle_exception
489      */
490     public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20, int $type = null,
491             bool $favourites = null) {
492         global $DB;
494         if (!is_null($type) && !in_array($type, [self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
495                 self::MESSAGE_CONVERSATION_TYPE_GROUP])) {
496             throw new \moodle_exception("Invalid value ($type) for type param, please see api constants.");
497         }
499         // We need to know which conversations are favourites, so we can either:
500         // 1) Include the 'isfavourite' attribute on conversations (when $favourite = null and we're including all conversations)
501         // 2) Restrict the results to ONLY those conversations which are favourites (when $favourite = true)
502         // 3) Restrict the results to ONLY those conversations which are NOT favourites (when $favourite = false).
503         $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
504         $favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
505         $favouriteconversationids = array_column($favouriteconversations, 'itemid');
506         if ($favourites && empty($favouriteconversationids)) {
507             return []; // If we are aiming to return ONLY favourites, and we have none, there's nothing more to do.
508         }
510         // CONVERSATIONS AND MOST RECENT MESSAGE.
511         // Include those conversations with messages first (ordered by most recent message, desc), then add any conversations which
512         // don't have messages, such as newly created group conversations.
513         // Because we're sorting by message 'timecreated', those conversations without messages could be at either the start or the
514         // end of the results (behaviour for sorting of nulls differs between DB vendors), so we use the case to presort these.
516         // If we need to return ONLY favourites, or NO favourites, generate the SQL snippet.
517         $favouritesql = "";
518         $favouriteparams = [];
519         if (null !== $favourites && !empty($favouriteconversationids)) {
520             list ($insql, $favouriteparams) =
521                     $DB->get_in_or_equal($favouriteconversationids, SQL_PARAMS_NAMED, 'favouriteids', $favourites);
522             $favouritesql = " AND mc.id {$insql} ";
523         }
525         // If we need to restrict type, generate the SQL snippet.
526         $typesql = !is_null($type) ? " AND mc.type = :convtype " : "";
528         $sql = "SELECT m.id as messageid, mc.id as id, mc.name as conversationname, mc.type as conversationtype, m.useridfrom,
529                        m.smallmessage, m.fullmessage, m.fullmessageformat, m.fullmessagehtml, m.timecreated, mc.component,
530                        mc.itemtype, mc.itemid
531                   FROM {message_conversations} mc
532             INNER JOIN {message_conversation_members} mcm
533                     ON (mcm.conversationid = mc.id AND mcm.userid = :userid3)
534             LEFT JOIN (
535                           SELECT m.conversationid, MAX(m.id) AS messageid
536                             FROM {messages} m
537                       INNER JOIN (
538                                       SELECT m.conversationid, MAX(m.timecreated) as maxtime
539                                         FROM {messages} m
540                                   INNER JOIN {message_conversation_members} mcm
541                                           ON mcm.conversationid = m.conversationid
542                                    LEFT JOIN {message_user_actions} mua
543                                           ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
544                                        WHERE mua.id is NULL
545                                          AND mcm.userid = :userid2
546                                     GROUP BY m.conversationid
547                                  ) maxmessage
548                                ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
549                          GROUP BY m.conversationid
550                        ) lastmessage
551                     ON lastmessage.conversationid = mc.id
552             LEFT JOIN {messages} m
553                    ON m.id = lastmessage.messageid
554                 WHERE mc.id IS NOT NULL $typesql $favouritesql
555               ORDER BY (CASE WHEN m.timecreated IS NULL THEN 0 ELSE 1 END) DESC, m.timecreated DESC, id DESC";
557         $params = array_merge($favouriteparams, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
558             'userid2' => $userid, 'userid3' => $userid, 'convtype' => $type]);
559         $conversationset = $DB->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
561         $conversations = [];
562         $uniquemembers = [];
563         $members = [];
564         foreach ($conversationset as $conversation) {
565             $conversations[] = $conversation;
566             $members[$conversation->id] = [];
567         }
568         $conversationset->close();
570         // If there are no conversations found, then return early.
571         if (empty($conversations)) {
572             return [];
573         }
575         // COMPONENT-LINKED CONVERSATION FIELDS.
576         // Conversations linked to components may have extra information, such as:
577         // - subname: Essentially a subtitle for the conversation. So you'd have "name: subname".
578         // - imageurl: A URL to the image for the linked conversation.
579         // For now, this is ONLY course groups.
580         $convextrafields = self::get_linked_conversation_extra_fields($conversations);
582         // MEMBERS.
583         // Ideally, we want to get 1 member for each conversation, but this depends on the type and whether there is a recent
584         // message or not.
585         //
586         // For 'individual' type conversations between 2 users, regardless of who sent the last message,
587         // we want the details of the other member in the conversation (i.e. not the current user).
588         //
589         // For 'group' type conversations, we want the details of the member who sent the last message, if there is one.
590         // This can be the current user or another group member, but for groups without messages, this will be empty.
591         //
592         // This also means that if type filtering is specified and only group conversations are returned, we don't need this extra
593         // query to get the 'other' user as we already have that information.
595         // Work out which members we have already, and which ones we might need to fetch.
596         // If all the last messages were from another user, then we don't need to fetch anything further.
597         foreach ($conversations as $conversation) {
598             if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
599                 if (!is_null($conversation->useridfrom) && $conversation->useridfrom != $userid) {
600                     $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
601                     $uniquemembers[$conversation->useridfrom] = $conversation->useridfrom;
602                 } else {
603                     $individualconversations[] = $conversation->id;
604                 }
605             } else if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
606                 // If we have a recent message, the sender is our member.
607                 if (!is_null($conversation->useridfrom)) {
608                     $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
609                     $uniquemembers[$conversation->useridfrom] = $conversation->useridfrom;
610                 }
611             }
612         }
613         // If we need to fetch any member information for any of the individual conversations.
614         // This is the case if any of the individual conversations have a recent message sent by the current user.
615         if (!empty($individualconversations)) {
616             list ($icidinsql, $icidinparams) = $DB->get_in_or_equal($individualconversations, SQL_PARAMS_NAMED, 'convid');
617             $indmembersql = "SELECT mcm.id, mcm.conversationid, mcm.userid
618                         FROM {message_conversation_members} mcm
619                        WHERE mcm.conversationid $icidinsql
620                        AND mcm.userid != :userid
621                        ORDER BY mcm.id";
622             $indmemberparams = array_merge($icidinparams, ['userid' => $userid]);
623             $conversationmembers = $DB->get_records_sql($indmembersql, $indmemberparams);
625             foreach ($conversationmembers as $mid => $member) {
626                 $members[$member->conversationid][$member->userid] = $member->userid;
627                 $uniquemembers[$member->userid] = $member->userid;
628             }
629         }
630         $memberids = array_values($uniquemembers);
632         // We could fail early here if we're sure that:
633         // a) we have no otherusers for all the conversations (users may have been deleted)
634         // b) we're sure that all conversations are individual (1:1).
636         // We need to pull out the list of users info corresponding to the memberids in the conversations.This
637         // needs to be done in a separate query to avoid doing a join on the messages tables and the user
638         // tables because on large sites these tables are massive which results in extremely slow
639         // performance (typically due to join buffer exhaustion).
640         if (!empty($memberids)) {
641             $memberinfo = helper::get_member_info($userid, $memberids);
643             // Update the members array with the member information.
644             $deletedmembers = [];
645             foreach ($members as $convid => $memberarr) {
646                 foreach ($memberarr as $key => $memberid) {
647                     if (array_key_exists($memberid, $memberinfo)) {
648                         // If the user is deleted, remember that.
649                         if ($memberinfo[$memberid]->isdeleted) {
650                             $deletedmembers[$convid][] = $memberid;
651                         }
652                         $members[$convid][$key] = $memberinfo[$memberid];
653                     }
654                 }
655             }
656         }
658         // MEMBER COUNT.
659         $cids = array_column($conversations, 'id');
660         list ($cidinsql, $cidinparams) = $DB->get_in_or_equal($cids, SQL_PARAMS_NAMED, 'convid');
661         $membercountsql = "SELECT conversationid, count(id) AS membercount
662                              FROM {message_conversation_members} mcm
663                             WHERE mcm.conversationid $cidinsql
664                          GROUP BY mcm.conversationid";
665         $membercounts = $DB->get_records_sql($membercountsql, $cidinparams);
667         // UNREAD MESSAGE COUNT.
668         // Finally, let's get the unread messages count for this user so that we can add it
669         // to the conversation. Remember we need to ignore the messages the user sent.
670         $unreadcountssql = 'SELECT m.conversationid, count(m.id) as unreadcount
671                               FROM {messages} m
672                         INNER JOIN {message_conversations} mc
673                                 ON mc.id = m.conversationid
674                         INNER JOIN {message_conversation_members} mcm
675                                 ON m.conversationid = mcm.conversationid
676                          LEFT JOIN {message_user_actions} mua
677                                 ON (mua.messageid = m.id AND mua.userid = ? AND
678                                    (mua.action = ? OR mua.action = ?))
679                              WHERE mcm.userid = ?
680                                AND m.useridfrom != ?
681                                AND mua.id is NULL
682                           GROUP BY m.conversationid';
683         $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
684             $userid, $userid]);
686         // Now, create the final return structure.
687         $arrconversations = [];
688         foreach ($conversations as $conversation) {
689             // Do not include any individual conversation which:
690             // a) Contains a deleted member or
691             // b) Does not contain a recent message for the user (this happens if the user has deleted all messages).
692             // Group conversations with deleted users or no messages are always returned.
693             if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL
694                     && (isset($deletedmembers[$conversation->id]) || empty($conversation->messageid))) {
695                 continue;
696             }
698             $conv = new \stdClass();
699             $conv->id = $conversation->id;
700             $conv->name = $conversation->conversationname;
701             $conv->subname = $convextrafields[$conv->id]['subname'] ?? null;
702             $conv->imageurl = $convextrafields[$conv->id]['imageurl'] ?? null;
703             $conv->type = $conversation->conversationtype;
704             $conv->membercount = $membercounts[$conv->id]->membercount;
705             $conv->isfavourite = in_array($conv->id, $favouriteconversationids);
706             $conv->isread = isset($unreadcounts[$conv->id]) ? false : true;
707             $conv->unreadcount = isset($unreadcounts[$conv->id]) ? $unreadcounts[$conv->id]->unreadcount : null;
708             $conv->members = $members[$conv->id];
710             // Add the most recent message information.
711             $conv->messages = [];
712             if ($conversation->smallmessage) {
713                 $msg = new \stdClass();
714                 $msg->id = $conversation->messageid;
715                 $msg->text = message_format_message_text($conversation);
716                 $msg->useridfrom = $conversation->useridfrom;
717                 $msg->timecreated = $conversation->timecreated;
718                 $conv->messages[] = $msg;
719             }
721             $arrconversations[] = $conv;
722         }
723         return $arrconversations;
724     }
726     /**
727      * Returns all conversations between two users
728      *
729      * @param int $userid1 One of the user's id
730      * @param int $userid2 The other user's id
731      * @param int $limitfrom
732      * @param int $limitnum
733      * @return array
734      * @throws \dml_exception
735      */
736     public static function get_conversations_between_users(int $userid1, int $userid2,
737                                                            int $limitfrom = 0, int $limitnum = 20) : array {
739         global $DB;
741         if ($userid1 == $userid2) {
742             return array();
743         }
745         // Get all conversation where both user1 and user2 are members.
746         // TODO: Add subname value. Waiting for definite table structure.
747         $sql = "SELECT mc.id, mc.type, mc.name, mc.timecreated
748                   FROM {message_conversations} mc
749             INNER JOIN {message_conversation_members} mcm1
750                     ON mc.id = mcm1.conversationid
751             INNER JOIN {message_conversation_members} mcm2
752                     ON mc.id = mcm2.conversationid
753                  WHERE mcm1.userid = :userid1
754                    AND mcm2.userid = :userid2
755                    AND mc.enabled != 0
756               ORDER BY mc.timecreated DESC";
758         return $DB->get_records_sql($sql, array('userid1' => $userid1, 'userid2' => $userid2), $limitfrom, $limitnum);
759     }
761     /**
762      * Mark a conversation as a favourite for the given user.
763      *
764      * @param int $conversationid the id of the conversation to mark as a favourite.
765      * @param int $userid the id of the user to whom the favourite belongs.
766      * @return favourite the favourite object.
767      * @throws \moodle_exception if the user or conversation don't exist.
768      */
769     public static function set_favourite_conversation(int $conversationid, int $userid) : favourite {
770         if (!self::is_user_in_conversation($userid, $conversationid)) {
771             throw new \moodle_exception("Conversation doesn't exist or user is not a member");
772         }
773         $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
774         return $ufservice->create_favourite('core_message', 'message_conversations', $conversationid, \context_system::instance());
775     }
777     /**
778      * Unset a conversation as a favourite for the given user.
779      *
780      * @param int $conversationid the id of the conversation to unset as a favourite.
781      * @param int $userid the id to whom the favourite belongs.
782      * @throws \moodle_exception if the favourite does not exist for the user.
783      */
784     public static function unset_favourite_conversation(int $conversationid, int $userid) {
785         $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
786         $ufservice->delete_favourite('core_message', 'message_conversations', $conversationid, \context_system::instance());
787     }
789     /**
790      * Returns the contacts to display in the contacts area.
791      *
792      * @param int $userid The user id
793      * @param int $limitfrom
794      * @param int $limitnum
795      * @return array
796      */
797     public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
798         global $DB;
800         $contactids = [];
801         $sql = "SELECT mc.*
802                   FROM {message_contacts} mc
803                  WHERE mc.userid = ? OR mc.contactid = ?
804               ORDER BY timecreated DESC";
805         if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
806             foreach ($contacts as $contact) {
807                 if ($userid == $contact->userid) {
808                     $contactids[] = $contact->contactid;
809                 } else {
810                     $contactids[] = $contact->userid;
811                 }
812             }
813         }
815         if (!empty($contactids)) {
816             list($insql, $inparams) = $DB->get_in_or_equal($contactids);
818             $sql = "SELECT u.*, mub.id as isblocked
819                       FROM {user} u
820                  LEFT JOIN {message_users_blocked} mub
821                         ON u.id = mub.blockeduserid
822                      WHERE u.id $insql";
823             if ($contacts = $DB->get_records_sql($sql, $inparams)) {
824                 $arrcontacts = [];
825                 foreach ($contacts as $contact) {
826                     $contact->blocked = $contact->isblocked ? 1 : 0;
827                     $arrcontacts[] = helper::create_contact($contact);
828                 }
830                 return $arrcontacts;
831             }
832         }
834         return [];
835     }
837     /**
838      * Returns the an array of the users the given user is in a conversation
839      * with who are a contact and the number of unread messages.
840      *
841      * @param int $userid The user id
842      * @param int $limitfrom
843      * @param int $limitnum
844      * @return array
845      */
846     public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
847         global $DB;
849         $userfields = \user_picture::fields('u', array('lastaccess'));
850         $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
851                               FROM {message_contacts} mc
852                         INNER JOIN {user} u
853                                 ON (u.id = mc.contactid OR u.id = mc.userid)
854                          LEFT JOIN {messages} m
855                                 ON ((m.useridfrom = mc.contactid OR m.useridfrom = mc.userid) AND m.useridfrom != ?)
856                          LEFT JOIN {message_conversation_members} mcm
857                                 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
858                          LEFT JOIN {message_user_actions} mua
859                                 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
860                          LEFT JOIN {message_users_blocked} mub
861                                 ON (mub.userid = ? AND mub.blockeduserid = u.id)
862                              WHERE mua.id is NULL
863                                AND mub.id is NULL
864                                AND (mc.userid = ? OR mc.contactid = ?)
865                                AND u.id != ?
866                                AND u.deleted = 0
867                           GROUP BY $userfields";
869         return $DB->get_records_sql($unreadcountssql, [$userid, $userid, $userid, self::MESSAGE_ACTION_READ,
870             $userid, $userid, $userid, $userid], $limitfrom, $limitnum);
871     }
873     /**
874      * Returns the an array of the users the given user is in a conversation
875      * with who are not a contact and the number of unread messages.
876      *
877      * @param int $userid The user id
878      * @param int $limitfrom
879      * @param int $limitnum
880      * @return array
881      */
882     public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
883         global $DB;
885         $userfields = \user_picture::fields('u', array('lastaccess'));
886         $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
887                               FROM {user} u
888                         INNER JOIN {messages} m
889                                 ON m.useridfrom = u.id
890                         INNER JOIN {message_conversation_members} mcm
891                                 ON mcm.conversationid = m.conversationid
892                          LEFT JOIN {message_user_actions} mua
893                                 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
894                          LEFT JOIN {message_contacts} mc
895                                 ON (mc.userid = ? AND mc.contactid = u.id)
896                          LEFT JOIN {message_users_blocked} mub
897                                 ON (mub.userid = ? AND mub.blockeduserid = u.id)
898                              WHERE mcm.userid = ?
899                                AND mcm.userid != m.useridfrom
900                                AND mua.id is NULL
901                                AND mub.id is NULL
902                                AND mc.id is NULL
903                                AND u.deleted = 0
904                           GROUP BY $userfields";
906         return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
907             $limitfrom, $limitnum);
908     }
910     /**
911      * Returns the messages to display in the message area.
912      *
913      * @deprecated since 3.6
914      * @param int $userid the current user
915      * @param int $otheruserid the other user
916      * @param int $limitfrom
917      * @param int $limitnum
918      * @param string $sort
919      * @param int $timefrom the time from the message being sent
920      * @param int $timeto the time up until the message being sent
921      * @return array
922      */
923     public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
924             $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
925         debugging('\core_message\api::get_messages() is deprecated, please use ' .
926             '\core_message\api::get_conversation_messages() instead.', DEBUG_DEVELOPER);
928         if (!empty($timefrom)) {
929             // Get the conversation between userid and otheruserid.
930             $userids = [$userid, $otheruserid];
931             if (!$conversationid = self::get_conversation_between_users($userids)) {
932                 // This method was always used for individual conversations.
933                 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
934                 $conversationid = $conversation->id;
935             }
937             // Check the cache to see if we even need to do a DB query.
938             $cache = \cache::make('core', 'message_time_last_message_between_users');
939             $key = helper::get_last_message_time_created_cache_key($conversationid);
940             $lastcreated = $cache->get($key);
942             // The last known message time is earlier than the one being requested so we can
943             // just return an empty result set rather than having to query the DB.
944             if ($lastcreated && $lastcreated < $timefrom) {
945                 return [];
946             }
947         }
949         $arrmessages = array();
950         if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
951                                              $sort, $timefrom, $timeto)) {
952             $arrmessages = helper::create_messages($userid, $messages);
953         }
955         return $arrmessages;
956     }
958     /**
959      * Returns the messages for the defined conversation.
960      *
961      * @param  int $userid The current user.
962      * @param  int $convid The conversation where the messages belong. Could be an object or just the id.
963      * @param  int $limitfrom Return a subset of records, starting at this point (optional).
964      * @param  int $limitnum Return a subset comprising this many records in total (optional, required if $limitfrom is set).
965      * @param  string $sort The column name to order by including optionally direction.
966      * @param  int $timefrom The time from the message being sent.
967      * @param  int $timeto The time up until the message being sent.
968      * @return array of messages
969      */
970     public static function get_conversation_messages(int $userid, int $convid, int $limitfrom = 0, int $limitnum = 0,
971         string $sort = 'timecreated ASC', int $timefrom = 0, int $timeto = 0) : array {
973         if (!empty($timefrom)) {
974             // Check the cache to see if we even need to do a DB query.
975             $cache = \cache::make('core', 'message_time_last_message_between_users');
976             $key = helper::get_last_message_time_created_cache_key($convid);
977             $lastcreated = $cache->get($key);
979             // The last known message time is earlier than the one being requested so we can
980             // just return an empty result set rather than having to query the DB.
981             if ($lastcreated && $lastcreated < $timefrom) {
982                 return [];
983             }
984         }
986         $arrmessages = array();
987         if ($messages = helper::get_conversation_messages($userid, $convid, 0, $limitfrom, $limitnum, $sort, $timefrom, $timeto)) {
988             $arrmessages = helper::format_conversation_messages($userid, $convid, $messages);
989         }
991         return $arrmessages;
992     }
994     /**
995      * Returns the most recent message between two users.
996      *
997      * @deprecated since 3.6
998      * @param int $userid the current user
999      * @param int $otheruserid the other user
1000      * @return \stdClass|null
1001      */
1002     public static function get_most_recent_message($userid, $otheruserid) {
1003         debugging('\core_message\api::get_most_recent_message() is deprecated, please use ' .
1004             '\core_message\api::get_most_recent_conversation_message() instead.', DEBUG_DEVELOPER);
1006         // We want two messages here so we get an accurate 'blocktime' value.
1007         if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
1008             // Swap the order so we now have them in historical order.
1009             $messages = array_reverse($messages);
1010             $arrmessages = helper::create_messages($userid, $messages);
1011             return array_pop($arrmessages);
1012         }
1014         return null;
1015     }
1017     /**
1018      * Returns the most recent message in a conversation.
1019      *
1020      * @param int $convid The conversation identifier.
1021      * @param int $currentuserid The current user identifier.
1022      * @return \stdClass|null The most recent message.
1023      */
1024     public static function get_most_recent_conversation_message(int $convid, int $currentuserid = 0) {
1025         global $USER;
1027         if (empty($currentuserid)) {
1028             $currentuserid = $USER->id;
1029         }
1031         if ($messages = helper::get_conversation_messages($currentuserid, $convid, 0, 0, 1, 'timecreated DESC')) {
1032             $convmessages = helper::format_conversation_messages($currentuserid, $convid, $messages);
1033             return array_pop($convmessages['messages']);
1034         }
1036         return null;
1037     }
1039     /**
1040      * Returns the profile information for a contact for a user.
1041      *
1042      * @param int $userid The user id
1043      * @param int $otheruserid The id of the user whose profile we want to view.
1044      * @return \stdClass
1045      */
1046     public static function get_profile($userid, $otheruserid) {
1047         global $CFG, $PAGE;
1049         require_once($CFG->dirroot . '/user/lib.php');
1051         $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
1053         // Create the data we are going to pass to the renderable.
1054         $data = new \stdClass();
1055         $data->userid = $otheruserid;
1056         $data->fullname = fullname($user);
1057         $data->city = '';
1058         $data->country = '';
1059         $data->email = '';
1060         $data->isonline = null;
1061         // Get the user picture data - messaging has always shown these to the user.
1062         $userpicture = new \user_picture($user);
1063         $userpicture->size = 1; // Size f1.
1064         $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
1065         $userpicture->size = 0; // Size f2.
1066         $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
1068         $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
1069         if ($userfields) {
1070             if (isset($userfields['city'])) {
1071                 $data->city = $userfields['city'];
1072             }
1073             if (isset($userfields['country'])) {
1074                 $data->country = $userfields['country'];
1075             }
1076             if (isset($userfields['email'])) {
1077                 $data->email = $userfields['email'];
1078             }
1079             if (isset($userfields['lastaccess'])) {
1080                 $data->isonline = helper::is_online($userfields['lastaccess']);
1081             }
1082         }
1084         $data->isblocked = self::is_blocked($userid, $otheruserid);
1085         $data->iscontact = self::is_contact($userid, $otheruserid);
1087         return $data;
1088     }
1090     /**
1091      * Checks if a user can delete messages they have either received or sent.
1092      *
1093      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1094      *  but will still seem as if it was by the user)
1095      * @param int $conversationid The id of the conversation
1096      * @return bool Returns true if a user can delete the conversation, false otherwise.
1097      */
1098     public static function can_delete_conversation(int $userid, int $conversationid = null) : bool {
1099         global $USER;
1101         if (is_null($conversationid)) {
1102             debugging('\core_message\api::can_delete_conversation() now expects a \'conversationid\' to be passed.',
1103                 DEBUG_DEVELOPER);
1104             return false;
1105         }
1107         $systemcontext = \context_system::instance();
1109         if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1110             return true;
1111         }
1113         if (!self::is_user_in_conversation($userid, $conversationid)) {
1114             return false;
1115         }
1117         if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1118                 $USER->id == $userid) {
1119             return true;
1120         }
1122         return false;
1123     }
1125     /**
1126      * Deletes a conversation.
1127      *
1128      * This function does not verify any permissions.
1129      *
1130      * @deprecated since 3.6
1131      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1132      *  but will still seem as if it was by the user)
1133      * @param int $otheruserid The id of the other user in the conversation
1134      * @return bool
1135      */
1136     public static function delete_conversation($userid, $otheruserid) {
1137         debugging('\core_message\api::delete_conversation() is deprecated, please use ' .
1138             '\core_message\api::delete_conversation_by_id() instead.', DEBUG_DEVELOPER);
1140         $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
1142         // If there is no conversation, there is nothing to do.
1143         if (!$conversationid) {
1144             return true;
1145         }
1147         self::delete_conversation_by_id($userid, $conversationid);
1149         return true;
1150     }
1152     /**
1153      * Deletes a conversation for a specified user.
1154      *
1155      * This function does not verify any permissions.
1156      *
1157      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1158      *  but will still seem as if it was by the user)
1159      * @param int $conversationid The id of the other user in the conversation
1160      */
1161     public static function delete_conversation_by_id(int $userid, int $conversationid) {
1162         global $DB, $USER;
1164         // Get all messages belonging to this conversation that have not already been deleted by this user.
1165         $sql = "SELECT m.*
1166                  FROM {messages} m
1167            INNER JOIN {message_conversations} mc
1168                    ON m.conversationid = mc.id
1169             LEFT JOIN {message_user_actions} mua
1170                    ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1171                 WHERE mua.id is NULL
1172                   AND mc.id = ?
1173              ORDER BY m.timecreated ASC";
1174         $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
1176         // Ok, mark these as deleted.
1177         foreach ($messages as $message) {
1178             $mua = new \stdClass();
1179             $mua->userid = $userid;
1180             $mua->messageid = $message->id;
1181             $mua->action = self::MESSAGE_ACTION_DELETED;
1182             $mua->timecreated = time();
1183             $mua->id = $DB->insert_record('message_user_actions', $mua);
1185             \core\event\message_deleted::create_from_ids($userid, $USER->id,
1186                 $message->id, $mua->id)->trigger();
1187         }
1188     }
1190     /**
1191      * Returns the count of unread conversations (collection of messages from a single user) for
1192      * the given user.
1193      *
1194      * @param \stdClass $user the user who's conversations should be counted
1195      * @return int the count of the user's unread conversations
1196      */
1197     public static function count_unread_conversations($user = null) {
1198         global $USER, $DB;
1200         if (empty($user)) {
1201             $user = $USER;
1202         }
1204         $sql = "SELECT COUNT(DISTINCT(m.conversationid))
1205                   FROM {messages} m
1206             INNER JOIN {message_conversations} mc
1207                     ON m.conversationid = mc.id
1208             INNER JOIN {message_conversation_members} mcm
1209                     ON mc.id = mcm.conversationid
1210              LEFT JOIN {message_user_actions} mua
1211                     ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1212                  WHERE mcm.userid = ?
1213                    AND mcm.userid != m.useridfrom
1214                    AND mua.id is NULL";
1216         return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
1217     }
1219     /**
1220      * Checks if a user can mark all messages as read.
1221      *
1222      * @param int $userid The user id of who we want to mark the messages for
1223      * @param int $conversationid The id of the conversation
1224      * @return bool true if user is permitted, false otherwise
1225      * @since 3.6
1226      */
1227     public static function can_mark_all_messages_as_read(int $userid, int $conversationid) : bool {
1228         global $USER;
1230         $systemcontext = \context_system::instance();
1232         if (has_capability('moodle/site:readallmessages', $systemcontext)) {
1233             return true;
1234         }
1236         if (!self::is_user_in_conversation($userid, $conversationid)) {
1237             return false;
1238         }
1240         if ($USER->id == $userid) {
1241             return true;
1242         }
1244         return false;
1245     }
1247     /**
1248      * Marks all messages being sent to a user in a particular conversation.
1249      *
1250      * If $conversationdid is null then it marks all messages as read sent to $userid.
1251      *
1252      * @param int $userid
1253      * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
1254      */
1255     public static function mark_all_messages_as_read($userid, $conversationid = null) {
1256         global $DB;
1258         $messagesql = "SELECT m.*
1259                          FROM {messages} m
1260                    INNER JOIN {message_conversations} mc
1261                            ON mc.id = m.conversationid
1262                    INNER JOIN {message_conversation_members} mcm
1263                            ON mcm.conversationid = mc.id
1264                     LEFT JOIN {message_user_actions} mua
1265                            ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1266                         WHERE mua.id is NULL
1267                           AND mcm.userid = ?
1268                           AND m.useridfrom != ?";
1269         $messageparams = [];
1270         $messageparams[] = $userid;
1271         $messageparams[] = self::MESSAGE_ACTION_READ;
1272         $messageparams[] = $userid;
1273         $messageparams[] = $userid;
1274         if (!is_null($conversationid)) {
1275             $messagesql .= " AND mc.id = ?";
1276             $messageparams[] = $conversationid;
1277         }
1279         $messages = $DB->get_recordset_sql($messagesql, $messageparams);
1280         foreach ($messages as $message) {
1281             self::mark_message_as_read($userid, $message);
1282         }
1283         $messages->close();
1284     }
1286     /**
1287      * Marks all notifications being sent from one user to another user as read.
1288      *
1289      * If the from user is null then it marks all notifications as read sent to the to user.
1290      *
1291      * @param int $touserid the id of the message recipient
1292      * @param int|null $fromuserid the id of the message sender, null if all messages
1293      * @return void
1294      */
1295     public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
1296         global $DB;
1298         $notificationsql = "SELECT n.*
1299                               FROM {notifications} n
1300                              WHERE useridto = ?
1301                                AND timeread is NULL";
1302         $notificationsparams = [$touserid];
1303         if (!empty($fromuserid)) {
1304             $notificationsql .= " AND useridfrom = ?";
1305             $notificationsparams[] = $fromuserid;
1306         }
1308         $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
1309         foreach ($notifications as $notification) {
1310             self::mark_notification_as_read($notification);
1311         }
1312         $notifications->close();
1313     }
1315     /**
1316      * Marks ALL messages being sent from $fromuserid to $touserid as read.
1317      *
1318      * Can be filtered by type.
1319      *
1320      * @deprecated since 3.5
1321      * @param int $touserid the id of the message recipient
1322      * @param int $fromuserid the id of the message sender
1323      * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
1324      * @return void
1325      */
1326     public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
1327         debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
1328             '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
1329             DEBUG_DEVELOPER);
1331         $type = strtolower($type);
1333         $conversationid = null;
1334         $ignoremessages = false;
1335         if (!empty($fromuserid)) {
1336             $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
1337             if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
1338                 $ignoremessages = true;
1339             }
1340         }
1342         if (!empty($type)) {
1343             if ($type == MESSAGE_TYPE_NOTIFICATION) {
1344                 self::mark_all_notifications_as_read($touserid, $fromuserid);
1345             } else if ($type == MESSAGE_TYPE_MESSAGE) {
1346                 if (!$ignoremessages) {
1347                     self::mark_all_messages_as_read($touserid, $conversationid);
1348                 }
1349             }
1350         } else { // We want both.
1351             self::mark_all_notifications_as_read($touserid, $fromuserid);
1352             if (!$ignoremessages) {
1353                 self::mark_all_messages_as_read($touserid, $conversationid);
1354             }
1355         }
1356     }
1358     /**
1359      * Returns message preferences.
1360      *
1361      * @param array $processors
1362      * @param array $providers
1363      * @param \stdClass $user
1364      * @return \stdClass
1365      * @since 3.2
1366      */
1367     public static function get_all_message_preferences($processors, $providers, $user) {
1368         $preferences = helper::get_providers_preferences($providers, $user->id);
1369         $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
1371         // For every processors put its options on the form (need to get function from processor's lib.php).
1372         foreach ($processors as $processor) {
1373             $processor->object->load_data($preferences, $user->id);
1374         }
1376         // Load general messaging preferences.
1377         $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
1378         $preferences->mailformat = $user->mailformat;
1379         $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
1381         return $preferences;
1382     }
1384     /**
1385      * Count the number of users blocked by a user.
1386      *
1387      * @param \stdClass $user The user object
1388      * @return int the number of blocked users
1389      */
1390     public static function count_blocked_users($user = null) {
1391         global $USER, $DB;
1393         if (empty($user)) {
1394             $user = $USER;
1395         }
1397         $sql = "SELECT count(mub.id)
1398                   FROM {message_users_blocked} mub
1399                  WHERE mub.userid = :userid";
1400         return $DB->count_records_sql($sql, array('userid' => $user->id));
1401     }
1403     /**
1404      * Determines if a user is permitted to send another user a private message.
1405      * If no sender is provided then it defaults to the logged in user.
1406      *
1407      * @param \stdClass $recipient The user object.
1408      * @param \stdClass|null $sender The user object.
1409      * @return bool true if user is permitted, false otherwise.
1410      */
1411     public static function can_post_message($recipient, $sender = null) {
1412         global $USER;
1414         if (is_null($sender)) {
1415             // The message is from the logged in user, unless otherwise specified.
1416             $sender = $USER;
1417         }
1419         $systemcontext = \context_system::instance();
1420         if (!has_capability('moodle/site:sendmessage', $systemcontext, $sender)) {
1421             return false;
1422         }
1424         if (has_capability('moodle/site:readallmessages', $systemcontext, $sender->id)) {
1425             return true;
1426         }
1428         // Check if the recipient can be messaged by the sender.
1429         return (self::can_contact_user($recipient, $sender));
1430     }
1432     /**
1433      * Get the messaging preference for a user.
1434      * If the user has not any messaging privacy preference:
1435      * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
1436      * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
1437      *
1438      * @param  int    $userid The user identifier.
1439      * @return int    The default messaging preference.
1440      */
1441     public static function get_user_privacy_messaging_preference(int $userid) : int {
1442         global $CFG;
1444         // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
1445         // otherwise, the default value will be "My contacts and anyone in my courses".
1446         if (empty($CFG->messagingallusers)) {
1447             $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
1448         } else {
1449             $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
1450         }
1451         $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $userid);
1453         // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
1454         // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1455         if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
1456             $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
1457         }
1459         return $privacypreference;
1460     }
1462     /**
1463      * Checks if the recipient is allowing messages from users that aren't a
1464      * contact. If not then it checks to make sure the sender is in the
1465      * recipient's contacts.
1466      *
1467      * @deprecated since 3.6
1468      * @param \stdClass $recipient The user object.
1469      * @param \stdClass|null $sender The user object.
1470      * @return bool true if $sender is blocked, false otherwise.
1471      */
1472     public static function is_user_non_contact_blocked($recipient, $sender = null) {
1473         debugging('\core_message\api::is_user_non_contact_blocked() is deprecated', DEBUG_DEVELOPER);
1475         global $USER, $CFG;
1477         if (is_null($sender)) {
1478             // The message is from the logged in user, unless otherwise specified.
1479             $sender = $USER;
1480         }
1482         $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1483         switch ($privacypreference) {
1484             case self::MESSAGE_PRIVACY_SITE:
1485                 if (!empty($CFG->messagingallusers)) {
1486                     // Users can be messaged without being contacts or members of the same course.
1487                     break;
1488                 }
1489                 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1490                 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1491             case self::MESSAGE_PRIVACY_COURSEMEMBER:
1492                 // Confirm the sender and the recipient are both members of the same course.
1493                 if (enrol_sharing_course($recipient, $sender)) {
1494                     // All good, the recipient and the sender are members of the same course.
1495                     return false;
1496                 }
1497             case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1498                 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1499                 return !self::is_contact($sender->id, $recipient->id);
1500         }
1502         return false;
1503     }
1505     /**
1506      * Checks if the recipient has specifically blocked the sending user.
1507      *
1508      * Note: This function will always return false if the sender has the
1509      * readallmessages capability at the system context level.
1510      *
1511      * @deprecated since 3.6
1512      * @param int $recipientid User ID of the recipient.
1513      * @param int $senderid User ID of the sender.
1514      * @return bool true if $sender is blocked, false otherwise.
1515      */
1516     public static function is_user_blocked($recipientid, $senderid = null) {
1517         debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1518             DEBUG_DEVELOPER);
1520         global $USER;
1522         if (is_null($senderid)) {
1523             // The message is from the logged in user, unless otherwise specified.
1524             $senderid = $USER->id;
1525         }
1527         $systemcontext = \context_system::instance();
1528         if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
1529             return false;
1530         }
1532         if (self::is_blocked($recipientid, $senderid)) {
1533             return true;
1534         }
1536         return false;
1537     }
1539     /**
1540      * Get specified message processor, validate corresponding plugin existence and
1541      * system configuration.
1542      *
1543      * @param string $name  Name of the processor.
1544      * @param bool $ready only return ready-to-use processors.
1545      * @return mixed $processor if processor present else empty array.
1546      * @since Moodle 3.2
1547      */
1548     public static function get_message_processor($name, $ready = false) {
1549         global $DB, $CFG;
1551         $processor = $DB->get_record('message_processors', array('name' => $name));
1552         if (empty($processor)) {
1553             // Processor not found, return.
1554             return array();
1555         }
1557         $processor = self::get_processed_processor_object($processor);
1558         if ($ready) {
1559             if ($processor->enabled && $processor->configured) {
1560                 return $processor;
1561             } else {
1562                 return array();
1563             }
1564         } else {
1565             return $processor;
1566         }
1567     }
1569     /**
1570      * Returns weather a given processor is enabled or not.
1571      * Note:- This doesn't check if the processor is configured or not.
1572      *
1573      * @param string $name Name of the processor
1574      * @return bool
1575      */
1576     public static function is_processor_enabled($name) {
1578         $cache = \cache::make('core', 'message_processors_enabled');
1579         $status = $cache->get($name);
1581         if ($status === false) {
1582             $processor = self::get_message_processor($name);
1583             if (!empty($processor)) {
1584                 $cache->set($name, $processor->enabled);
1585                 return $processor->enabled;
1586             } else {
1587                 return false;
1588             }
1589         }
1591         return $status;
1592     }
1594     /**
1595      * Set status of a processor.
1596      *
1597      * @param \stdClass $processor processor record.
1598      * @param 0|1 $enabled 0 or 1 to set the processor status.
1599      * @return bool
1600      * @since Moodle 3.2
1601      */
1602     public static function update_processor_status($processor, $enabled) {
1603         global $DB;
1604         $cache = \cache::make('core', 'message_processors_enabled');
1605         $cache->delete($processor->name);
1606         return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1607     }
1609     /**
1610      * Given a processor object, loads information about it's settings and configurations.
1611      * This is not a public api, instead use @see \core_message\api::get_message_processor()
1612      * or @see \get_message_processors()
1613      *
1614      * @param \stdClass $processor processor object
1615      * @return \stdClass processed processor object
1616      * @since Moodle 3.2
1617      */
1618     public static function get_processed_processor_object(\stdClass $processor) {
1619         global $CFG;
1621         $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1622         if (is_readable($processorfile)) {
1623             include_once($processorfile);
1624             $processclass = 'message_output_' . $processor->name;
1625             if (class_exists($processclass)) {
1626                 $pclass = new $processclass();
1627                 $processor->object = $pclass;
1628                 $processor->configured = 0;
1629                 if ($pclass->is_system_configured()) {
1630                     $processor->configured = 1;
1631                 }
1632                 $processor->hassettings = 0;
1633                 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1634                     $processor->hassettings = 1;
1635                 }
1636                 $processor->available = 1;
1637             } else {
1638                 print_error('errorcallingprocessor', 'message');
1639             }
1640         } else {
1641             $processor->available = 0;
1642         }
1643         return $processor;
1644     }
1646     /**
1647      * Retrieve users blocked by $user1
1648      *
1649      * @param int $userid The user id of the user whos blocked users we are returning
1650      * @return array the users blocked
1651      */
1652     public static function get_blocked_users($userid) {
1653         global $DB;
1655         $userfields = \user_picture::fields('u', array('lastaccess'));
1656         $blockeduserssql = "SELECT $userfields
1657                               FROM {message_users_blocked} mub
1658                         INNER JOIN {user} u
1659                                 ON u.id = mub.blockeduserid
1660                              WHERE u.deleted = 0
1661                                AND mub.userid = ?
1662                           GROUP BY $userfields
1663                           ORDER BY u.firstname ASC";
1664         return $DB->get_records_sql($blockeduserssql, [$userid]);
1665     }
1667     /**
1668      * Mark a single message as read.
1669      *
1670      * @param int $userid The user id who marked the message as read
1671      * @param \stdClass $message The message
1672      * @param int|null $timeread The time the message was marked as read, if null will default to time()
1673      */
1674     public static function mark_message_as_read($userid, $message, $timeread = null) {
1675         global $DB;
1677         if (is_null($timeread)) {
1678             $timeread = time();
1679         }
1681         $mua = new \stdClass();
1682         $mua->userid = $userid;
1683         $mua->messageid = $message->id;
1684         $mua->action = self::MESSAGE_ACTION_READ;
1685         $mua->timecreated = $timeread;
1686         $mua->id = $DB->insert_record('message_user_actions', $mua);
1688         // Get the context for the user who received the message.
1689         $context = \context_user::instance($userid, IGNORE_MISSING);
1690         // If the user no longer exists the context value will be false, in this case use the system context.
1691         if ($context === false) {
1692             $context = \context_system::instance();
1693         }
1695         // Trigger event for reading a message.
1696         $event = \core\event\message_viewed::create(array(
1697             'objectid' => $mua->id,
1698             'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1699             'context' => $context,
1700             'relateduserid' => $message->useridfrom,
1701             'other' => array(
1702                 'messageid' => $message->id
1703             )
1704         ));
1705         $event->trigger();
1706     }
1708     /**
1709      * Mark a single notification as read.
1710      *
1711      * @param \stdClass $notification The notification
1712      * @param int|null $timeread The time the message was marked as read, if null will default to time()
1713      */
1714     public static function mark_notification_as_read($notification, $timeread = null) {
1715         global $DB;
1717         if (is_null($timeread)) {
1718             $timeread = time();
1719         }
1721         if (is_null($notification->timeread)) {
1722             $updatenotification = new \stdClass();
1723             $updatenotification->id = $notification->id;
1724             $updatenotification->timeread = $timeread;
1726             $DB->update_record('notifications', $updatenotification);
1728             // Trigger event for reading a notification.
1729             \core\event\notification_viewed::create_from_ids(
1730                 $notification->useridfrom,
1731                 $notification->useridto,
1732                 $notification->id
1733             )->trigger();
1734         }
1735     }
1737     /**
1738      * Checks if a user can delete a message.
1739      *
1740      * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1741      *  but will still seem as if it was by the user)
1742      * @param int $messageid The message id
1743      * @return bool Returns true if a user can delete the message, false otherwise.
1744      */
1745     public static function can_delete_message($userid, $messageid) {
1746         global $DB, $USER;
1748         $systemcontext = \context_system::instance();
1750         $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
1752         if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1753             return true;
1754         }
1756         if (!self::is_user_in_conversation($userid, $conversationid)) {
1757             return false;
1758         }
1760         if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1761                 $USER->id == $userid) {
1762             return true;
1763         }
1765         return false;
1766     }
1768     /**
1769      * Deletes a message.
1770      *
1771      * This function does not verify any permissions.
1772      *
1773      * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1774      *  but will still seem as if it was by the user)
1775      * @param int $messageid The message id
1776      * @return bool
1777      */
1778     public static function delete_message($userid, $messageid) {
1779         global $DB, $USER;
1781         if (!$DB->record_exists('messages', ['id' => $messageid])) {
1782             return false;
1783         }
1785         // Check if the user has already deleted this message.
1786         if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1787                 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1788             $mua = new \stdClass();
1789             $mua->userid = $userid;
1790             $mua->messageid = $messageid;
1791             $mua->action = self::MESSAGE_ACTION_DELETED;
1792             $mua->timecreated = time();
1793             $mua->id = $DB->insert_record('message_user_actions', $mua);
1795             // Trigger event for deleting a message.
1796             \core\event\message_deleted::create_from_ids($userid, $USER->id,
1797                 $messageid, $mua->id)->trigger();
1799             return true;
1800         }
1802         return false;
1803     }
1805     /**
1806      * Returns the conversation between two users.
1807      *
1808      * @param array $userids
1809      * @return int|bool The id of the conversation, false if not found
1810      */
1811     public static function get_conversation_between_users(array $userids) {
1812         global $DB;
1814         $hash = helper::get_conversation_hash($userids);
1816         $params = [
1817             'type' => self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1818             'convhash' => $hash
1819         ];
1820         if ($conversation = $DB->get_record('message_conversations', $params)) {
1821             return $conversation->id;
1822         }
1824         return false;
1825     }
1827     /**
1828      * Creates a conversation between two users.
1829      *
1830      * @deprecated since 3.6
1831      * @param array $userids
1832      * @return int The id of the conversation
1833      */
1834     public static function create_conversation_between_users(array $userids) {
1835         debugging('\core_message\api::create_conversation_between_users is deprecated, please use ' .
1836             '\core_message\api::create_conversation instead.', DEBUG_DEVELOPER);
1838         // This method was always used for individual conversations.
1839         $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
1841         return $conversation->id;
1842     }
1844     /**
1845      * Creates a conversation with selected users and messages.
1846      *
1847      * @param int $type The type of conversation
1848      * @param int[] $userids The array of users to add to the conversation
1849      * @param string|null $name The name of the conversation
1850      * @param int $enabled Determines if the conversation is created enabled or disabled
1851      * @param string|null $component Defines the Moodle component which the conversation belongs to, if any
1852      * @param string|null $itemtype Defines the type of the component
1853      * @param int|null $itemid The id of the component
1854      * @param int|null $contextid The id of the context
1855      * @return \stdClass
1856      */
1857     public static function create_conversation(int $type, array $userids, string $name = null,
1858             int $enabled = self::MESSAGE_CONVERSATION_ENABLED, string $component = null,
1859             string $itemtype = null, int $itemid = null, int $contextid = null) {
1861         global $DB;
1863         // Sanity check.
1864         if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1865             if (count($userids) > 2) {
1866                 throw new \moodle_exception('An individual conversation can not have more than two users.');
1867             }
1868         }
1870         $conversation = new \stdClass();
1871         $conversation->type = $type;
1872         $conversation->name = $name;
1873         $conversation->convhash = null;
1874         if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1875             $conversation->convhash = helper::get_conversation_hash($userids);
1876         }
1877         $conversation->component = $component;
1878         $conversation->itemtype = $itemtype;
1879         $conversation->itemid = $itemid;
1880         $conversation->contextid = $contextid;
1881         $conversation->enabled = $enabled;
1882         $conversation->timecreated = time();
1883         $conversation->timemodified = $conversation->timecreated;
1884         $conversation->id = $DB->insert_record('message_conversations', $conversation);
1886         // Add users to this conversation.
1887         $arrmembers = [];
1888         foreach ($userids as $userid) {
1889             $member = new \stdClass();
1890             $member->conversationid = $conversation->id;
1891             $member->userid = $userid;
1892             $member->timecreated = time();
1893             $member->id = $DB->insert_record('message_conversation_members', $member);
1895             $arrmembers[] = $member;
1896         }
1898         $conversation->members = $arrmembers;
1900         return $conversation;
1901     }
1903     /**
1904      * Checks if a user can create a group conversation.
1905      *
1906      * @param int $userid The id of the user attempting to create the conversation
1907      * @param \context $context The context they are creating the conversation from, most likely course context
1908      * @return bool
1909      */
1910     public static function can_create_group_conversation(int $userid, \context $context) : bool {
1911         global $CFG;
1913         // If we can't message at all, then we can't create a conversation.
1914         if (empty($CFG->messaging)) {
1915             return false;
1916         }
1918         // We need to check they have the capability to create the conversation.
1919         return has_capability('moodle/course:creategroupconversations', $context, $userid);
1920     }
1922     /**
1923      * Checks if a user can create a contact request.
1924      *
1925      * @param int $userid The id of the user who is creating the contact request
1926      * @param int $requesteduserid The id of the user being requested
1927      * @return bool
1928      */
1929     public static function can_create_contact(int $userid, int $requesteduserid) : bool {
1930         global $CFG;
1932         // If we can't message at all, then we can't create a contact.
1933         if (empty($CFG->messaging)) {
1934             return false;
1935         }
1937         // If we can message anyone on the site then we can create a contact.
1938         if ($CFG->messagingallusers) {
1939             return true;
1940         }
1942         // We need to check if they are in the same course.
1943         return enrol_sharing_course($userid, $requesteduserid);
1944     }
1946     /**
1947      * Handles creating a contact request.
1948      *
1949      * @param int $userid The id of the user who is creating the contact request
1950      * @param int $requesteduserid The id of the user being requested
1951      */
1952     public static function create_contact_request(int $userid, int $requesteduserid) {
1953         global $DB;
1955         $request = new \stdClass();
1956         $request->userid = $userid;
1957         $request->requesteduserid = $requesteduserid;
1958         $request->timecreated = time();
1960         $DB->insert_record('message_contact_requests', $request);
1962         // Send a notification.
1963         $userfrom = \core_user::get_user($userid);
1964         $userfromfullname = fullname($userfrom);
1965         $userto = \core_user::get_user($requesteduserid);
1966         $url = new \moodle_url('/message/pendingcontactrequests.php');
1968         $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
1969         $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);
1971         $message = new \core\message\message();
1972         $message->courseid = SITEID;
1973         $message->component = 'moodle';
1974         $message->name = 'messagecontactrequests';
1975         $message->notification = 1;
1976         $message->userfrom = $userfrom;
1977         $message->userto = $userto;
1978         $message->subject = $subject;
1979         $message->fullmessage = text_to_html($fullmessage);
1980         $message->fullmessageformat = FORMAT_HTML;
1981         $message->fullmessagehtml = $fullmessage;
1982         $message->smallmessage = '';
1983         $message->contexturl = $url->out(false);
1985         message_send($message);
1986     }
1989     /**
1990      * Handles confirming a contact request.
1991      *
1992      * @param int $userid The id of the user who created the contact request
1993      * @param int $requesteduserid The id of the user confirming the request
1994      */
1995     public static function confirm_contact_request(int $userid, int $requesteduserid) {
1996         global $DB;
1998         if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1999                 'requesteduserid' => $requesteduserid])) {
2000             self::add_contact($userid, $requesteduserid);
2002             $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2003         }
2004     }
2006     /**
2007      * Handles declining a contact request.
2008      *
2009      * @param int $userid The id of the user who created the contact request
2010      * @param int $requesteduserid The id of the user declining the request
2011      */
2012     public static function decline_contact_request(int $userid, int $requesteduserid) {
2013         global $DB;
2015         if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2016                 'requesteduserid' => $requesteduserid])) {
2017             $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2018         }
2019     }
2021     /**
2022      * Handles returning the contact requests for a user.
2023      *
2024      * This also includes the user data necessary to display information
2025      * about the user.
2026      *
2027      * It will not include blocked users.
2028      *
2029      * @param int $userid
2030      * @return array The list of contact requests
2031      */
2032     public static function get_contact_requests(int $userid) : array {
2033         global $DB;
2035         $ufields = \user_picture::fields('u');
2036         $sql = "SELECT $ufields, mcr.id as contactrequestid
2037                   FROM {user} u
2038                   JOIN {message_contact_requests} mcr
2039                     ON u.id = mcr.userid
2040              LEFT JOIN {message_users_blocked} mub
2041                     ON (mub.userid = ? AND mub.blockeduserid = u.id)
2042                  WHERE mcr.requesteduserid = ?
2043                    AND u.deleted = 0
2044                    AND mub.id is NULL
2045               ORDER BY mcr.timecreated DESC";
2047         return $DB->get_records_sql($sql, [$userid, $userid]);
2048     }
2050     /**
2051      * Handles adding a contact.
2052      *
2053      * @param int $userid The id of the user who requested to be a contact
2054      * @param int $contactid The id of the contact
2055      */
2056     public static function add_contact(int $userid, int $contactid) {
2057         global $DB;
2059         $messagecontact = new \stdClass();
2060         $messagecontact->userid = $userid;
2061         $messagecontact->contactid = $contactid;
2062         $messagecontact->timecreated = time();
2063         $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
2065         $eventparams = [
2066             'objectid' => $messagecontact->id,
2067             'userid' => $userid,
2068             'relateduserid' => $contactid,
2069             'context' => \context_user::instance($userid)
2070         ];
2071         $event = \core\event\message_contact_added::create($eventparams);
2072         $event->add_record_snapshot('message_contacts', $messagecontact);
2073         $event->trigger();
2074     }
2076     /**
2077      * Handles removing a contact.
2078      *
2079      * @param int $userid The id of the user who is removing a user as a contact
2080      * @param int $contactid The id of the user to be removed as a contact
2081      */
2082     public static function remove_contact(int $userid, int $contactid) {
2083         global $DB;
2085         if ($contact = self::get_contact($userid, $contactid)) {
2086             $DB->delete_records('message_contacts', ['id' => $contact->id]);
2088             $event = \core\event\message_contact_removed::create(array(
2089                 'objectid' => $contact->id,
2090                 'userid' => $userid,
2091                 'relateduserid' => $contactid,
2092                 'context' => \context_user::instance($userid)
2093             ));
2094             $event->add_record_snapshot('message_contacts', $contact);
2095             $event->trigger();
2096         }
2097     }
2099     /**
2100      * Handles blocking a user.
2101      *
2102      * @param int $userid The id of the user who is blocking
2103      * @param int $usertoblockid The id of the user being blocked
2104      */
2105     public static function block_user(int $userid, int $usertoblockid) {
2106         global $DB;
2108         $blocked = new \stdClass();
2109         $blocked->userid = $userid;
2110         $blocked->blockeduserid = $usertoblockid;
2111         $blocked->timecreated = time();
2112         $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
2114         // Trigger event for blocking a contact.
2115         $event = \core\event\message_user_blocked::create(array(
2116             'objectid' => $blocked->id,
2117             'userid' => $userid,
2118             'relateduserid' => $usertoblockid,
2119             'context' => \context_user::instance($userid)
2120         ));
2121         $event->add_record_snapshot('message_users_blocked', $blocked);
2122         $event->trigger();
2123     }
2125     /**
2126      * Handles unblocking a user.
2127      *
2128      * @param int $userid The id of the user who is unblocking
2129      * @param int $usertounblockid The id of the user being unblocked
2130      */
2131     public static function unblock_user(int $userid, int $usertounblockid) {
2132         global $DB;
2134         if ($blockeduser = $DB->get_record('message_users_blocked',
2135                 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
2136             $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
2138             // Trigger event for unblocking a contact.
2139             $event = \core\event\message_user_unblocked::create(array(
2140                 'objectid' => $blockeduser->id,
2141                 'userid' => $userid,
2142                 'relateduserid' => $usertounblockid,
2143                 'context' => \context_user::instance($userid)
2144             ));
2145             $event->add_record_snapshot('message_users_blocked', $blockeduser);
2146             $event->trigger();
2147         }
2148     }
2150     /**
2151      * Checks if users are already contacts.
2152      *
2153      * @param int $userid The id of one of the users
2154      * @param int $contactid The id of the other user
2155      * @return bool Returns true if they are a contact, false otherwise
2156      */
2157     public static function is_contact(int $userid, int $contactid) : bool {
2158         global $DB;
2160         $sql = "SELECT id
2161                   FROM {message_contacts} mc
2162                  WHERE (mc.userid = ? AND mc.contactid = ?)
2163                     OR (mc.userid = ? AND mc.contactid = ?)";
2164         return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
2165     }
2167     /**
2168      * Returns the row in the database table message_contacts that represents the contact between two people.
2169      *
2170      * @param int $userid The id of one of the users
2171      * @param int $contactid The id of the other user
2172      * @return mixed A fieldset object containing the record, false otherwise
2173      */
2174     public static function get_contact(int $userid, int $contactid) {
2175         global $DB;
2177         $sql = "SELECT mc.*
2178                   FROM {message_contacts} mc
2179                  WHERE (mc.userid = ? AND mc.contactid = ?)
2180                     OR (mc.userid = ? AND mc.contactid = ?)";
2181         return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
2182     }
2184     /**
2185      * Checks if a user is already blocked.
2186      *
2187      * @param int $userid
2188      * @param int $blockeduserid
2189      * @return bool Returns true if they are a blocked, false otherwise
2190      */
2191     public static function is_blocked(int $userid, int $blockeduserid) : bool {
2192         global $DB;
2194         return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
2195     }
2197     /**
2198      * Checks if a contact request already exists between users.
2199      *
2200      * @param int $userid The id of the user who is creating the contact request
2201      * @param int $requesteduserid The id of the user being requested
2202      * @return bool Returns true if a contact request exists, false otherwise
2203      */
2204     public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
2205         global $DB;
2207         $sql = "SELECT id
2208                   FROM {message_contact_requests} mcr
2209                  WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
2210                     OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
2211         return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
2212     }
2214     /**
2215      * Checks if a user is already in a conversation.
2216      *
2217      * @param int $userid The id of the user we want to check if they are in a group
2218      * @param int $conversationid The id of the conversation
2219      * @return bool Returns true if a contact request exists, false otherwise
2220      */
2221     public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
2222         global $DB;
2224         return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
2225             'userid' => $userid]);
2226     }
2228     /**
2229      * Checks if the sender can message the recipient.
2230      *
2231      * @param \stdClass $recipient The user object.
2232      * @param \stdClass $sender The user object.
2233      * @return bool true if recipient hasn't blocked sender and sender can contact to recipient, false otherwise.
2234      */
2235     protected static function can_contact_user(\stdClass $recipient, \stdClass $sender) : bool {
2236         if (has_capability('moodle/site:messageanyuser', \context_system::instance(), $sender->id)) {
2237             // The sender has the ability to contact any user across the entire site.
2238             return true;
2239         }
2241         // The initial value of $cancontact is null to indicate that a value has not been determined.
2242         $cancontact = null;
2244         if (self::is_blocked($recipient->id, $sender->id)) {
2245             // The recipient has specifically blocked this sender.
2246             $cancontact = false;
2247         }
2249         $sharedcourses = null;
2250         if (null === $cancontact) {
2251             // There are three user preference options:
2252             // - Site: Allow anyone not explicitly blocked to contact me;
2253             // - Course members: Allow anyone I am in a course with to contact me; and
2254             // - Contacts: Only allow my contacts to contact me.
2255             //
2256             // The Site option is only possible when the messagingallusers site setting is also enabled.
2258             $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
2259             if (self::MESSAGE_PRIVACY_SITE === $privacypreference) {
2260                 // The user preference is to allow any user to contact them.
2261                 // No need to check anything else.
2262                 $cancontact = true;
2263             } else {
2264                 // This user only allows their own contacts, and possibly course peers, to contact them.
2265                 // If the users are contacts then we can avoid the more expensive shared courses check.
2266                 $cancontact = self::is_contact($sender->id, $recipient->id);
2268                 if (!$cancontact && self::MESSAGE_PRIVACY_COURSEMEMBER === $privacypreference) {
2269                     // The users are not contacts and the user allows course member messaging.
2270                     // Check whether these two users share any course together.
2271                     $sharedcourses = enrol_get_shared_courses($recipient->id, $sender->id, true);
2272                     $cancontact = (!empty($sharedcourses));
2273                 }
2274             }
2275         }
2277         if (false === $cancontact) {
2278             // At the moment the users cannot contact one another.
2279             // Check whether the messageanyuser capability applies in any of the shared courses.
2280             // This is intended to allow teachers to message students regardless of message settings.
2282             // Note: You cannot use empty($sharedcourses) here because this may be an empty array.
2283             if (null === $sharedcourses) {
2284                 $sharedcourses = enrol_get_shared_courses($recipient->id, $sender->id, true);
2285             }
2287             foreach ($sharedcourses as $course) {
2288                 // Note: enrol_get_shared_courses will preload any shared context.
2289                 if (has_capability('moodle/site:messageanyuser', \context_course::instance($course->id), $sender->id)) {
2290                     $cancontact = true;
2291                     break;
2292                 }
2293             }
2294         }
2296         return $cancontact;
2297     }
2299     /**
2300      * Add some new members to an existing conversation.
2301      *
2302      * @param array $userids User ids array to add as members.
2303      * @param int $convid The conversation id. Must exists.
2304      * @throws \dml_missing_record_exception If convid conversation doesn't exist
2305      * @throws \dml_exception If there is a database error
2306      * @throws \moodle_exception If trying to add a member(s) to a non-group conversation
2307      */
2308     public static function add_members_to_conversation(array $userids, int $convid) {
2309         global $DB;
2311         $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2313         // We can only add members to a group conversation.
2314         if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2315             throw new \moodle_exception('You can not add members to a non-group conversation.');
2316         }
2318         // Be sure we are not trying to add a non existing user to the conversation. Work only with existing users.
2319         list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2320         $existingusers = $DB->get_fieldset_select('user', 'id', "id $useridcondition", $params);
2322         // Be sure we are not adding a user is already member of the conversation. Take all the members.
2323         $memberuserids = array_values($DB->get_records_menu(
2324             'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
2325         );
2327         // Work with existing new members.
2328         $members = array();
2329         $newuserids = array_diff($existingusers, $memberuserids);
2330         foreach ($newuserids as $userid) {
2331             $member = new \stdClass();
2332             $member->conversationid = $convid;
2333             $member->userid = $userid;
2334             $member->timecreated = time();
2335             $members[] = $member;
2336         }
2338         $DB->insert_records('message_conversation_members', $members);
2339     }
2341     /**
2342      * Remove some members from an existing conversation.
2343      *
2344      * @param array $userids The user ids to remove from conversation members.
2345      * @param int $convid The conversation id. Must exists.
2346      * @throws \dml_exception
2347      * @throws \moodle_exception If trying to remove a member(s) from a non-group conversation
2348      */
2349     public static function remove_members_from_conversation(array $userids, int $convid) {
2350         global $DB;
2352         $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2354         if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2355             throw new \moodle_exception('You can not remove members from a non-group conversation.');
2356         }
2358         list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2359         $params['convid'] = $convid;
2361         $DB->delete_records_select('message_conversation_members',
2362             "conversationid = :convid AND userid $useridcondition", $params);
2363     }
2365     /**
2366      * Count conversation members.
2367      *
2368      * @param int $convid The conversation id.
2369      * @return int Number of conversation members.
2370      * @throws \dml_exception
2371      */
2372     public static function count_conversation_members(int $convid) : int {
2373         global $DB;
2375         return $DB->count_records('message_conversation_members', ['conversationid' => $convid]);
2376     }
2378     /**
2379      * Checks whether or not a conversation area is enabled.
2380      *
2381      * @param string $component Defines the Moodle component which the area was added to.
2382      * @param string $itemtype Defines the type of the component.
2383      * @param int $itemid The id of the component.
2384      * @param int $contextid The id of the context.
2385      * @return bool Returns if a conversation area exists and is enabled, false otherwise
2386      */
2387     public static function is_conversation_area_enabled(string $component, string $itemtype, int $itemid, int $contextid) : bool {
2388         global $DB;
2390         return $DB->record_exists('message_conversations',
2391             [
2392                 'itemid' => $itemid,
2393                 'contextid' => $contextid,
2394                 'component' => $component,
2395                 'itemtype' => $itemtype,
2396                 'enabled' => self::MESSAGE_CONVERSATION_ENABLED
2397             ]
2398         );
2399     }
2401     /**
2402      * Get conversation by area.
2403      *
2404      * @param string $component Defines the Moodle component which the area was added to.
2405      * @param string $itemtype Defines the type of the component.
2406      * @param int $itemid The id of the component.
2407      * @param int $contextid The id of the context.
2408      * @return \stdClass
2409      */
2410     public static function get_conversation_by_area(string $component, string $itemtype, int $itemid, int $contextid) {
2411         global $DB;
2413         return $DB->get_record('message_conversations',
2414             [
2415                 'itemid' => $itemid,
2416                 'contextid' => $contextid,
2417                 'component' => $component,
2418                 'itemtype'  => $itemtype
2419             ]
2420         );
2421     }
2423     /**
2424      * Enable a conversation.
2425      *
2426      * @param int $conversationid The id of the conversation.
2427      * @return void
2428      */
2429     public static function enable_conversation(int $conversationid) {
2430         global $DB;
2432         $conversation = new \stdClass();
2433         $conversation->id = $conversationid;
2434         $conversation->enabled = self::MESSAGE_CONVERSATION_ENABLED;
2435         $conversation->timemodified = time();
2436         $DB->update_record('message_conversations', $conversation);
2437     }
2439     /**
2440      * Disable a conversation.
2441      *
2442      * @param int $conversationid The id of the conversation.
2443      * @return void
2444      */
2445     public static function disable_conversation(int $conversationid) {
2446         global $DB;
2448         $conversation = new \stdClass();
2449         $conversation->id = $conversationid;
2450         $conversation->enabled = self::MESSAGE_CONVERSATION_DISABLED;
2451         $conversation->timemodified = time();
2452         $DB->update_record('message_conversations', $conversation);
2453     }
2455     /**
2456      * Update the name of a conversation.
2457      *
2458      * @param int $conversationid The id of a conversation.
2459      * @param string $name The main name of the area
2460      * @return void
2461      */
2462     public static function update_conversation_name(int $conversationid, string $name) {
2463         global $DB;
2465         if ($conversation = $DB->get_record('message_conversations', array('id' => $conversationid))) {
2466             if ($name <> $conversation->name) {
2467                 $conversation->name = $name;
2468                 $conversation->timemodified = time();
2469                 $DB->update_record('message_conversations', $conversation);
2470             }
2471         }
2472     }
2474     /**
2475      * Returns a list of conversation members.
2476      *
2477      * @param int $userid The user we are returning the conversation members for, used by helper::get_member_info.
2478      * @param int $conversationid The id of the conversation
2479      * @param bool $includecontactrequests Do we want to include contact requests with this data?
2480      * @param int $limitfrom
2481      * @param int $limitnum
2482      * @return array
2483      */
2484     public static function get_conversation_members(int $userid, int $conversationid, bool $includecontactrequests = false,
2485                                                     int $limitfrom = 0, int $limitnum = 0) : array {
2486         global $DB;
2488         if ($members = $DB->get_records('message_conversation_members', ['conversationid' => $conversationid],
2489                 'timecreated ASC, id ASC', 'userid', $limitfrom, $limitnum)) {
2490             $userids = array_keys($members);
2491             $members = helper::get_member_info($userid, $userids);
2493             // Check if we want to include contact requests as well.
2494             if ($includecontactrequests) {
2495                 list($useridsql, $usersparams) = $DB->get_in_or_equal($userids);
2497                 $wheresql = "(userid $useridsql OR requesteduserid $useridsql)";
2498                 if ($contactrequests = $DB->get_records_select('message_contact_requests', $wheresql,
2499                         array_merge($usersparams, $usersparams), 'timecreated ASC, id ASC')) {
2500                     foreach ($contactrequests as $contactrequest) {
2501                         if (isset($members[$contactrequest->userid])) {
2502                             $members[$contactrequest->userid]->contactrequests[] = $contactrequest;
2503                         }
2504                         if (isset($members[$contactrequest->requesteduserid])) {
2505                             $members[$contactrequest->requesteduserid]->contactrequests[] = $contactrequest;
2506                         }
2507                     }
2508                 }
2509             }
2511             return $members;
2512         }
2514         return [];
2515     }