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