MDL-64412 core_message: remove ordering code from message_search_users()
[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
f8b46dab 312 $params = array('search' => '%' . $DB->sql_like_escape($search) . '%', 'userid1' => $userid, 'userid2' => $userid);
548cac7d
AA
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
a3a6e3c9 326 $contacts = [];
548cac7d
AA
327 if (!empty($foundusers)) {
328 $contacts = helper::get_member_info($userid, array_keys($foundusers));
a3a6e3c9
JD
329 foreach ($contacts as $memberuserid => $memberinfo) {
330 $contacts[$memberuserid]->conversations = self::get_conversations_between_users($userid, $memberuserid, 0, 1000);
cd03b8d7
MN
331 }
332 }
333
548cac7d 334 // Let's get those non-contacts.
41485be2 335 // If site wide messaging is enabled, we just fetch any matched users which are non-contacts.
548cac7d 336 if ($CFG->messagingallusers) {
548cac7d 337 $sql = "SELECT u.id
41485be2
JD
338 FROM {user} u
339 WHERE u.deleted = 0
340 AND u.confirmed = 1
341 AND " . $DB->sql_like($fullname, ':search', false) . "
342 AND u.id $exclude
343 AND NOT EXISTS (SELECT mc.id
344 FROM {message_contacts} mc
345 WHERE (mc.userid = u.id AND mc.contactid = :userid1)
346 OR (mc.userid = :userid2 AND mc.contactid = u.id))
347 ORDER BY " . $DB->sql_fullname();
348
349 $foundusers = $DB->get_records_sql($sql, $params + $excludeparams, $limitfrom, $limitnum);
548cac7d 350 } else {
41485be2
JD
351 require_once($CFG->dirroot . '/user/lib.php');
352 // If site-wide messaging is disabled, then we should only be able to search for users who we are allowed to see.
353 // Because we can't achieve all the required visibility checks in SQL, we'll iterate through the non-contact records
354 // and stop once we have enough matching the 'visible' criteria.
355 // TODO: MDL-63983 - Improve the performance of non-contact searches when site-wide messaging is disabled (default).
356
357 // Use a local generator to achieve this iteration.
358 $getnoncontactusers = function ($limitfrom = 0, $limitnum = 0) use($fullname, $exclude, $params, $excludeparams) {
359 global $DB;
360 $sql = "SELECT u.*
548cac7d 361 FROM {user} u
548cac7d
AA
362 WHERE u.deleted = 0
363 AND u.confirmed = 1
364 AND " . $DB->sql_like($fullname, ':search', false) . "
365 AND u.id $exclude
366 AND NOT EXISTS (SELECT mc.id
367 FROM {message_contacts} mc
368 WHERE (mc.userid = u.id AND mc.contactid = :userid1)
369 OR (mc.userid = :userid2 AND mc.contactid = u.id))
370 ORDER BY " . $DB->sql_fullname();
41485be2
JD
371 while ($records = $DB->get_records_sql($sql, $params + $excludeparams, $limitfrom, $limitnum)) {
372 yield $records;
373 $limitfrom += $limitnum;
374 }
375 };
376
377 // Fetch in batches of $limitnum * 2 to improve the chances of matching a user without going back to the DB.
378 // The generator cannot function without a sensible limiter, so set one if this is not set.
379 $batchlimit = ($limitnum == 0) ? 20 : $limitnum;
380
381 // We need to make the offset param work with the generator.
382 // Basically, if we want to get say 10 records starting at the 40th record, we need to see 50 records and return only
383 // those after the 40th record. We can never pass the method's offset param to the generator as we need to manage the
384 // position within those valid records ourselves.
385 // See MDL-63983 dealing with performance improvements to this area of code.
386 $noofvalidseenrecords = 0;
387 $returnedusers = [];
388 foreach ($getnoncontactusers(0, $batchlimit) as $users) {
389 foreach ($users as $id => $user) {
390 $userdetails = \user_get_user_details_courses($user);
391
392 // Return the user only if the searched field is returned.
393 // Otherwise it means that the $USER was not allowed to search the returned user.
394 if (!empty($userdetails) and !empty($userdetails['fullname'])) {
395 // We know we've matched, but only save the record if it's within the offset area we need.
396 if ($limitfrom == 0) {
397 // No offset specified, so just save.
398 $returnedusers[$id] = $user;
399 } else {
400 // There is an offset in play.
401 // If we've passed enough records already (> offset value), then we can save this one.
402 if ($noofvalidseenrecords >= $limitfrom) {
403 $returnedusers[$id] = $user;
404 }
405 }
406 if (count($returnedusers) == $limitnum) {
407 break 2;
408 }
409 $noofvalidseenrecords++;
410 }
411 }
412 }
413 $foundusers = $returnedusers;
548cac7d 414 }
548cac7d 415
a3a6e3c9 416 $noncontacts = [];
548cac7d
AA
417 if (!empty($foundusers)) {
418 $noncontacts = helper::get_member_info($userid, array_keys($foundusers));
a3a6e3c9
JD
419 foreach ($noncontacts as $memberuserid => $memberinfo) {
420 $noncontacts[$memberuserid]->conversations = self::get_conversations_between_users($userid, $memberuserid, 0, 1000);
548cac7d
AA
421 }
422 }
423
a3a6e3c9 424 return array(array_values($contacts), array_values($noncontacts));
cd03b8d7
MN
425 }
426
eb5865da 427 /**
003cdcce 428 * Gets extra fields, like image url and subname for any conversations linked to components.
eb5865da
JD
429 *
430 * The subname is like a subtitle for the conversation, to compliment it's name.
003cdcce 431 * 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
432 *
433 * @param array $conversations a list of conversations records.
434 * @return array the array of subnames, index by conversation id.
003cdcce
JD
435 * @throws \coding_exception
436 * @throws \dml_exception
eb5865da 437 */
003cdcce 438 protected static function get_linked_conversation_extra_fields(array $conversations) : array {
442f1425
BB
439 global $DB, $PAGE;
440
441 $renderer = $PAGE->get_renderer('core');
eb5865da
JD
442
443 $linkedconversations = [];
444 foreach ($conversations as $conversation) {
445 if (!is_null($conversation->component) && !is_null($conversation->itemtype)) {
446 $linkedconversations[$conversation->component][$conversation->itemtype][$conversation->id]
447 = $conversation->itemid;
448 }
449 }
450 if (empty($linkedconversations)) {
451 return [];
452 }
453
454 // TODO: MDL-63814: Working out the subname for linked conversations should be done in a generic way.
455 // Get the itemid, but only for course group linked conversation for now.
003cdcce 456 $extrafields = [];
eb5865da
JD
457 if (!empty($linkeditems = $linkedconversations['core_group']['groups'])) { // Format: [conversationid => itemid].
458 // Get the name of the course to which the group belongs.
459 list ($groupidsql, $groupidparams) = $DB->get_in_or_equal(array_values($linkeditems), SQL_PARAMS_NAMED, 'groupid');
003cdcce 460 $sql = "SELECT g.*, c.shortname as courseshortname
eb5865da
JD
461 FROM {groups} g
462 JOIN {course} c
463 ON g.courseid = c.id
464 WHERE g.id $groupidsql";
465 $courseinfo = $DB->get_records_sql($sql, $groupidparams);
466 foreach ($linkeditems as $convid => $groupid) {
467 if (array_key_exists($groupid, $courseinfo)) {
003cdcce
JD
468 $group = $courseinfo[$groupid];
469 // Subname.
470 $extrafields[$convid]['subname'] = format_string($courseinfo[$groupid]->courseshortname);
471
472 // Imageurl.
442f1425 473 $extrafields[$convid]['imageurl'] = $renderer->image_url('g/g1')->out(false); // default image.
9cef5491
JD
474 if ($url = get_group_picture_url($group, $group->courseid, true)) {
475 $extrafields[$convid]['imageurl'] = $url->out(false);
476 }
eb5865da
JD
477 }
478 }
479 }
003cdcce 480 return $extrafields;
eb5865da
JD
481 }
482
483
879e2bef
MN
484 /**
485 * Returns the contacts and their conversation to display in the contacts area.
486 *
349f4261
RW
487 * ** WARNING **
488 * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
489 * to retrieve too much information in a single call will cause performance problems.
490 * ** WARNING **
491 *
492 * This function has specifically been altered to break each of the data sets it
493 * requires into separate database calls. This is to avoid the performance problems
494 * observed when attempting to join large data sets (e.g. the message tables and
495 * the user table).
496 *
497 * While it is possible to gather the data in a single query, and it may even be
498 * more efficient with a correctly tuned database, we have opted to trade off some of
499 * the benefits of a single query in order to ensure this function will work on
500 * most databases with default tunings and with large data sets.
501 *
879e2bef 502 * @param int $userid The user id
879e2bef
MN
503 * @param int $limitfrom
504 * @param int $limitnum
eb5865da
JD
505 * @param int $type the type of the conversation, if you wish to filter to a certain type (see api constants).
506 * @param bool $favourites whether to include NO favourites (false) or ONLY favourites (true), or null to ignore this setting.
507 * @return array the array of conversations
508 * @throws \moodle_exception
879e2bef 509 */
b8ff2c44 510 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20, int $type = null,
eb5865da 511 bool $favourites = null) {
349f4261
RW
512 global $DB;
513
eb5865da
JD
514 if (!is_null($type) && !in_array($type, [self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
515 self::MESSAGE_CONVERSATION_TYPE_GROUP])) {
516 throw new \moodle_exception("Invalid value ($type) for type param, please see api constants.");
517 }
518
519 // We need to know which conversations are favourites, so we can either:
520 // 1) Include the 'isfavourite' attribute on conversations (when $favourite = null and we're including all conversations)
521 // 2) Restrict the results to ONLY those conversations which are favourites (when $favourite = true)
522 // 3) Restrict the results to ONLY those conversations which are NOT favourites (when $favourite = false).
523 $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
524 $favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
525 $favouriteconversationids = array_column($favouriteconversations, 'itemid');
526 if ($favourites && empty($favouriteconversationids)) {
527 return []; // If we are aiming to return ONLY favourites, and we have none, there's nothing more to do.
528 }
529
530 // CONVERSATIONS AND MOST RECENT MESSAGE.
531 // Include those conversations with messages first (ordered by most recent message, desc), then add any conversations which
532 // don't have messages, such as newly created group conversations.
533 // Because we're sorting by message 'timecreated', those conversations without messages could be at either the start or the
534 // end of the results (behaviour for sorting of nulls differs between DB vendors), so we use the case to presort these.
535
536 // If we need to return ONLY favourites, or NO favourites, generate the SQL snippet.
b8ff2c44
JD
537 $favouritesql = "";
538 $favouriteparams = [];
e926b4d0
AN
539 if (null !== $favourites && !empty($favouriteconversationids)) {
540 list ($insql, $favouriteparams) =
541 $DB->get_in_or_equal($favouriteconversationids, SQL_PARAMS_NAMED, 'favouriteids', $favourites);
542 $favouritesql = " AND mc.id {$insql} ";
b8ff2c44
JD
543 }
544
eb5865da
JD
545 // If we need to restrict type, generate the SQL snippet.
546 $typesql = !is_null($type) ? " AND mc.type = :convtype " : "";
547
548 $sql = "SELECT m.id as messageid, mc.id as id, mc.name as conversationname, mc.type as conversationtype, m.useridfrom,
74fc14e5
JD
549 m.smallmessage, m.fullmessage, m.fullmessageformat, m.fullmessagehtml, m.timecreated, mc.component,
550 mc.itemtype, mc.itemid
eb5865da
JD
551 FROM {message_conversations} mc
552 INNER JOIN {message_conversation_members} mcm
553 ON (mcm.conversationid = mc.id AND mcm.userid = :userid3)
554 LEFT JOIN (
555 SELECT m.conversationid, MAX(m.id) AS messageid
883ce421
MN
556 FROM {messages} m
557 INNER JOIN (
558 SELECT m.conversationid, MAX(m.timecreated) as maxtime
559 FROM {messages} m
560 INNER JOIN {message_conversation_members} mcm
561 ON mcm.conversationid = m.conversationid
562 LEFT JOIN {message_user_actions} mua
563 ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
564 WHERE mua.id is NULL
565 AND mcm.userid = :userid2
566 GROUP BY m.conversationid
567 ) maxmessage
568 ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
569 GROUP BY m.conversationid
570 ) lastmessage
eb5865da
JD
571 ON lastmessage.conversationid = mc.id
572 LEFT JOIN {messages} m
573 ON m.id = lastmessage.messageid
18550c0a
JD
574 WHERE mc.id IS NOT NULL
575 AND mc.enabled = 1 $typesql $favouritesql
eb5865da 576 ORDER BY (CASE WHEN m.timecreated IS NULL THEN 0 ELSE 1 END) DESC, m.timecreated DESC, id DESC";
b8ff2c44
JD
577
578 $params = array_merge($favouriteparams, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
eb5865da
JD
579 'userid2' => $userid, 'userid3' => $userid, 'convtype' => $type]);
580 $conversationset = $DB->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
581
582 $conversations = [];
cb389619 583 $selfconversations = []; // Used to track legacy conversations with one's self (both conv members the same user).
eb5865da 584 $members = [];
cef1d977
MN
585 $individualmembers = [];
586 $groupmembers = [];
eb5865da 587 foreach ($conversationset as $conversation) {
cef1d977 588 $conversations[$conversation->id] = $conversation;
eb5865da 589 $members[$conversation->id] = [];
349f4261 590 }
eb5865da 591 $conversationset->close();
349f4261 592
eb5865da
JD
593 // If there are no conversations found, then return early.
594 if (empty($conversations)) {
883ce421
MN
595 return [];
596 }
597
003cdcce
JD
598 // COMPONENT-LINKED CONVERSATION FIELDS.
599 // Conversations linked to components may have extra information, such as:
600 // - subname: Essentially a subtitle for the conversation. So you'd have "name: subname".
601 // - imageurl: A URL to the image for the linked conversation.
eb5865da 602 // For now, this is ONLY course groups.
003cdcce 603 $convextrafields = self::get_linked_conversation_extra_fields($conversations);
eb5865da
JD
604
605 // MEMBERS.
606 // Ideally, we want to get 1 member for each conversation, but this depends on the type and whether there is a recent
607 // message or not.
608 //
609 // For 'individual' type conversations between 2 users, regardless of who sent the last message,
610 // we want the details of the other member in the conversation (i.e. not the current user).
cb389619
JD
611 // The only exception to the 'not the current user' rule is for 'self' conversations - a legacy construct in which a user
612 // can message themselves via user bulk actions. Subsequently, there are 2 records for the same user created in the members
613 // table.
eb5865da
JD
614 //
615 // For 'group' type conversations, we want the details of the member who sent the last message, if there is one.
616 // This can be the current user or another group member, but for groups without messages, this will be empty.
617 //
618 // This also means that if type filtering is specified and only group conversations are returned, we don't need this extra
619 // query to get the 'other' user as we already have that information.
620
621 // Work out which members we have already, and which ones we might need to fetch.
622 // If all the last messages were from another user, then we don't need to fetch anything further.
623 foreach ($conversations as $conversation) {
624 if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
625 if (!is_null($conversation->useridfrom) && $conversation->useridfrom != $userid) {
626 $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
cef1d977 627 $individualmembers[$conversation->useridfrom] = $conversation->useridfrom;
eb5865da
JD
628 } else {
629 $individualconversations[] = $conversation->id;
630 }
631 } else if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
632 // If we have a recent message, the sender is our member.
633 if (!is_null($conversation->useridfrom)) {
634 $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
cef1d977 635 $groupmembers[$conversation->useridfrom] = $conversation->useridfrom;
eb5865da
JD
636 }
637 }
638 }
639 // If we need to fetch any member information for any of the individual conversations.
640 // This is the case if any of the individual conversations have a recent message sent by the current user.
641 if (!empty($individualconversations)) {
642 list ($icidinsql, $icidinparams) = $DB->get_in_or_equal($individualconversations, SQL_PARAMS_NAMED, 'convid');
643 $indmembersql = "SELECT mcm.id, mcm.conversationid, mcm.userid
644 FROM {message_conversation_members} mcm
645 WHERE mcm.conversationid $icidinsql
646 AND mcm.userid != :userid
647 ORDER BY mcm.id";
648 $indmemberparams = array_merge($icidinparams, ['userid' => $userid]);
649 $conversationmembers = $DB->get_records_sql($indmembersql, $indmemberparams);
650
651 foreach ($conversationmembers as $mid => $member) {
652 $members[$member->conversationid][$member->userid] = $member->userid;
cef1d977 653 $individualmembers[$member->userid] = $member->userid;
eb5865da 654 }
cb389619
JD
655
656 // Self conversations: If any of the individual conversations which were missing members are still missing members,
657 // we know these must be 'self' conversations. This is a legacy scenario, created via user bulk actions.
658 // In such cases, the member returned should be the current user.
659 //
660 // NOTE: Currently, these conversations are not returned by this method, however,
661 // identifying them is important for future reference.
662 foreach ($individualconversations as $indconvid) {
663 if (empty($members[$indconvid])) {
664 // Keep track of the self conversation (for future use).
665 $selfconversations[$indconvid] = $indconvid;
666
667 // Set the member to the current user.
668 $members[$indconvid][$userid] = $userid;
669 $individualmembers[$userid] = $userid;
670 }
671 }
eb5865da 672 }
eb5865da
JD
673
674 // We could fail early here if we're sure that:
675 // a) we have no otherusers for all the conversations (users may have been deleted)
676 // b) we're sure that all conversations are individual (1:1).
677
678 // We need to pull out the list of users info corresponding to the memberids in the conversations.This
349f4261
RW
679 // needs to be done in a separate query to avoid doing a join on the messages tables and the user
680 // tables because on large sites these tables are massive which results in extremely slow
681 // performance (typically due to join buffer exhaustion).
cef1d977
MN
682 if (!empty($individualmembers) || !empty($groupmembers)) {
683 // Now, we want to remove any duplicates from the group members array. For individual members we will
684 // be doing a more extensive call as we want their contact requests as well as privacy information,
685 // which is not necessary for group conversations.
686 $diffgroupmembers = array_diff($groupmembers, $individualmembers);
687
688 $individualmemberinfo = helper::get_member_info($userid, $individualmembers, true, true);
689 $groupmemberinfo = helper::get_member_info($userid, $diffgroupmembers);
690
691 // Don't use array_merge, as we lose array keys.
692 $memberinfo = $individualmemberinfo + $groupmemberinfo;
eb5865da
JD
693
694 // Update the members array with the member information.
695 $deletedmembers = [];
696 foreach ($members as $convid => $memberarr) {
697 foreach ($memberarr as $key => $memberid) {
698 if (array_key_exists($memberid, $memberinfo)) {
699 // If the user is deleted, remember that.
700 if ($memberinfo[$memberid]->isdeleted) {
701 $deletedmembers[$convid][] = $memberid;
702 }
cef1d977
MN
703
704 $members[$convid][$key] = clone $memberinfo[$memberid];
705
706 if ($conversations[$convid]->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
707 // Remove data we don't need for group.
708 $members[$convid][$key]->requirescontact = null;
709 $members[$convid][$key]->canmessage = null;
710 $members[$convid][$key]->contactrequests = [];
711 }
eb5865da
JD
712 }
713 }
714 }
883ce421
MN
715 }
716
eb5865da
JD
717 // MEMBER COUNT.
718 $cids = array_column($conversations, 'id');
719 list ($cidinsql, $cidinparams) = $DB->get_in_or_equal($cids, SQL_PARAMS_NAMED, 'convid');
cb389619 720 $membercountsql = "SELECT conversationid, count(DISTINCT userid) AS membercount
eb5865da
JD
721 FROM {message_conversation_members} mcm
722 WHERE mcm.conversationid $cidinsql
723 GROUP BY mcm.conversationid";
724 $membercounts = $DB->get_records_sql($membercountsql, $cidinparams);
725
726 // UNREAD MESSAGE COUNT.
727 // Finally, let's get the unread messages count for this user so that we can add it
883ce421 728 // to the conversation. Remember we need to ignore the messages the user sent.
eb5865da 729 $unreadcountssql = 'SELECT m.conversationid, count(m.id) as unreadcount
883ce421
MN
730 FROM {messages} m
731 INNER JOIN {message_conversations} mc
732 ON mc.id = m.conversationid
733 INNER JOIN {message_conversation_members} mcm
734 ON m.conversationid = mcm.conversationid
735 LEFT JOIN {message_user_actions} mua
736 ON (mua.messageid = m.id AND mua.userid = ? AND
737 (mua.action = ? OR mua.action = ?))
738 WHERE mcm.userid = ?
739 AND m.useridfrom != ?
740 AND mua.id is NULL
eb5865da 741 GROUP BY m.conversationid';
883ce421
MN
742 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
743 $userid, $userid]);
744
eb5865da
JD
745 // Now, create the final return structure.
746 $arrconversations = [];
747 foreach ($conversations as $conversation) {
0847aa12
JD
748 // Do not include any individual conversations which do not contain a recent message for the user.
749 // This happens if the user has deleted all messages.
aa748351
JD
750 // Group conversations with deleted users or no messages are always returned.
751 if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL
0847aa12 752 && (empty($conversation->messageid))) {
883ce421
MN
753 continue;
754 }
755
425f5adc
JD
756 // Exclude 'self' conversations for now.
757 if (isset($selfconversations[$conversation->id])) {
758 continue;
759 }
760
eb5865da
JD
761 $conv = new \stdClass();
762 $conv->id = $conversation->id;
763 $conv->name = $conversation->conversationname;
003cdcce
JD
764 $conv->subname = $convextrafields[$conv->id]['subname'] ?? null;
765 $conv->imageurl = $convextrafields[$conv->id]['imageurl'] ?? null;
eb5865da
JD
766 $conv->type = $conversation->conversationtype;
767 $conv->membercount = $membercounts[$conv->id]->membercount;
768 $conv->isfavourite = in_array($conv->id, $favouriteconversationids);
769 $conv->isread = isset($unreadcounts[$conv->id]) ? false : true;
770 $conv->unreadcount = isset($unreadcounts[$conv->id]) ? $unreadcounts[$conv->id]->unreadcount : null;
771 $conv->members = $members[$conv->id];
772
773 // Add the most recent message information.
774 $conv->messages = [];
775 if ($conversation->smallmessage) {
776 $msg = new \stdClass();
777 $msg->id = $conversation->messageid;
74fc14e5 778 $msg->text = message_format_message_text($conversation);
eb5865da
JD
779 $msg->useridfrom = $conversation->useridfrom;
780 $msg->timecreated = $conversation->timecreated;
781 $conv->messages[] = $msg;
349f4261
RW
782 }
783
eb5865da 784 $arrconversations[] = $conv;
879e2bef 785 }
de55cb1b 786 return $arrconversations;
879e2bef
MN
787 }
788
548cac7d
AA
789 /**
790 * Returns all conversations between two users
791 *
792 * @param int $userid1 One of the user's id
793 * @param int $userid2 The other user's id
794 * @param int $limitfrom
795 * @param int $limitnum
796 * @return array
797 * @throws \dml_exception
798 */
799 public static function get_conversations_between_users(int $userid1, int $userid2,
800 int $limitfrom = 0, int $limitnum = 20) : array {
801
802 global $DB;
803
804 if ($userid1 == $userid2) {
805 return array();
806 }
807
808 // Get all conversation where both user1 and user2 are members.
809 // TODO: Add subname value. Waiting for definite table structure.
810 $sql = "SELECT mc.id, mc.type, mc.name, mc.timecreated
811 FROM {message_conversations} mc
812 INNER JOIN {message_conversation_members} mcm1
813 ON mc.id = mcm1.conversationid
814 INNER JOIN {message_conversation_members} mcm2
815 ON mc.id = mcm2.conversationid
816 WHERE mcm1.userid = :userid1
817 AND mcm2.userid = :userid2
818 AND mc.enabled != 0
819 ORDER BY mc.timecreated DESC";
820
821 return $DB->get_records_sql($sql, array('userid1' => $userid1, 'userid2' => $userid2), $limitfrom, $limitnum);
822 }
823
4e313026
RW
824 /**
825 * Return a conversation.
826 *
827 * @param int $userid The user id to get the conversation for
828 * @param int $conversationid The id of the conversation to fetch
829 * @param bool $includecontactrequests Should contact requests be included between members
830 * @param bool $includeprivacyinfo Should privacy info be included between members
831 * @param int $memberlimit Limit number of members to load
832 * @param int $memberoffset Offset members by this amount
833 * @param int $messagelimit Limit number of messages to load
834 * @param int $messageoffset Offset the messages
835 * @param bool $newestmessagesfirst Order messages by newest first
836 * @return \stdClass
837 */
838 public static function get_conversation(
839 int $userid,
840 int $conversationid,
841 bool $includecontactrequests = false,
842 bool $includeprivacyinfo = false,
843 int $memberlimit = 0,
844 int $memberoffset = 0,
845 int $messagelimit = 0,
846 int $messageoffset = 0,
847 bool $newestmessagesfirst = true
848 ) {
849 global $USER, $DB;
850
851 $systemcontext = \context_system::instance();
852 $canreadallmessages = has_capability('moodle/site:readallmessages', $systemcontext);
853 if (($USER->id != $userid) && !$canreadallmessages) {
854 throw new \moodle_exception('You do not have permission to perform this action.');
855 }
856
857 $conversation = $DB->get_record('message_conversations', ['id' => $conversationid]);
858 if (!$conversation) {
859 return null;
860 }
861
e4125485
JD
862 // Get the context of the conversation. This will be used to check whether the conversation is a favourite.
863 // This will be either 'user' (for individual conversations) or, in the case of linked conversations,
864 // the context stored in the record.
865 $userctx = \context_user::instance($userid);
866 $conversationctx = empty($conversation->contextid) ? $userctx : \context::instance_by_id($conversation->contextid);
867
4e313026
RW
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));
e4125485 902 $isfavourite = $service->favourite_exists('core_message', 'message_conversations', $conversationid, $conversationctx);
4e313026
RW
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 = ?
7c8ba89d 1479 AND mc.enabled = ?
883ce421
MN
1480 AND mcm.userid != m.useridfrom
1481 AND mua.id is NULL";
1482
7c8ba89d
MN
1483 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id,
1484 self::MESSAGE_CONVERSATION_ENABLED]);
79f6c36c
MN
1485 }
1486
abf7a261
MN
1487 /**
1488 * Checks if a user can mark all messages as read.
1489 *
1490 * @param int $userid The user id of who we want to mark the messages for
1491 * @param int $conversationid The id of the conversation
1492 * @return bool true if user is permitted, false otherwise
1493 * @since 3.6
1494 */
1495 public static function can_mark_all_messages_as_read(int $userid, int $conversationid) : bool {
1496 global $USER;
1497
1498 $systemcontext = \context_system::instance();
1499
1500 if (has_capability('moodle/site:readallmessages', $systemcontext)) {
1501 return true;
1502 }
1503
1504 if (!self::is_user_in_conversation($userid, $conversationid)) {
1505 return false;
1506 }
1507
1508 if ($USER->id == $userid) {
1509 return true;
1510 }
1511
1512 return false;
1513 }
1514
6399c7ef
RW
1515 /**
1516 * Returns the count of conversations (collection of messages from a single user) for
1517 * the given user.
1518 *
8e91aaab
JD
1519 * @param int $userid The user whose conversations should be counted.
1520 * @return array the array of conversations counts, indexed by type.
6399c7ef 1521 */
8e91aaab 1522 public static function get_conversation_counts(int $userid) : array {
6399c7ef
RW
1523 global $DB;
1524
8e91aaab
JD
1525 // Some restrictions we need to be aware of:
1526 // - Individual conversations containing soft-deleted user must be counted.
1527 // - Individual conversations containing only deleted messages must NOT be counted.
7f6f45c4 1528 // - Individual conversations which are legacy 'self' conversations (2 members, both the same user) must NOT be counted.
8e91aaab
JD
1529 // - Group conversations with 0 messages must be counted.
1530 // - Linked conversations which are disabled (enabled = 0) must NOT be counted.
1531 // - Any type of conversation can be included in the favourites count, however, the type counts and the favourites count
1532 // are mutually exclusive; any conversations which are counted in favourites cannot be counted elsewhere.
1533
1534 // First, ask the favourites service to give us the join SQL for favourited conversations,
1535 // so we can include favourite information in the query.
1536 $usercontext = \context_user::instance($userid);
1537 $favservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
1538 list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_message', 'message_conversations', 'fav', 'mc.id');
1539
1540 $sql = "SELECT mc.type, fav.itemtype, COUNT(DISTINCT mc.id) as count
1541 FROM {message_conversations} mc
1542 INNER JOIN {message_conversation_members} mcm
1543 ON mcm.conversationid = mc.id
7f6f45c4
JD
1544 INNER JOIN (
1545 SELECT mcm.conversationid, count(distinct mcm.userid) as membercount
1546 FROM {message_conversation_members} mcm
1547 WHERE mcm.conversationid IN (
1548 SELECT DISTINCT conversationid
1549 FROM {message_conversation_members} mcm2
1550 WHERE userid = :userid5
1551 )
1552 GROUP BY mcm.conversationid
1553 ) uniquemembercount
1554 ON uniquemembercount.conversationid = mc.id
8e91aaab
JD
1555 LEFT JOIN (
1556 SELECT m.conversationid as convid, MAX(m.timecreated) as maxtime
1557 FROM {messages} m
1558 INNER JOIN {message_conversation_members} mcm
1559 ON mcm.conversationid = m.conversationid
1560 LEFT JOIN {message_user_actions} mua
1561 ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
1562 WHERE mua.id is NULL
1563 AND mcm.userid = :userid2
1564 GROUP BY m.conversationid
1565 ) maxvisibleconvmessage
1566 ON maxvisibleconvmessage.convid = mc.id
1567 $favsql
1568 WHERE mcm.userid = :userid3
1569 AND mc.enabled = :enabled
7f6f45c4
JD
1570 AND (
1571 (mc.type = :individualtype AND maxvisibleconvmessage.convid IS NOT NULL AND membercount > 1) OR
1572 (mc.type = :grouptype)
1573 )
8e91aaab
JD
1574 GROUP BY mc.type, fav.itemtype
1575 ORDER BY mc.type ASC";
1576
1577 $params = [
1578 'userid' => $userid,
1579 'userid2' => $userid,
1580 'userid3' => $userid,
1581 'userid4' => $userid,
7f6f45c4 1582 'userid5' => $userid,
8e91aaab
JD
1583 'action' => self::MESSAGE_ACTION_DELETED,
1584 'enabled' => self::MESSAGE_CONVERSATION_ENABLED,
1585 'individualtype' => self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1586 'grouptype' => self::MESSAGE_CONVERSATION_TYPE_GROUP,
1587 ] + $favparams;
1588
1589 // Assemble the return array.
1590 $counts = [
1591 'favourites' => 0,
1592 'types' => [
1593 self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL => 0,
1594 self::MESSAGE_CONVERSATION_TYPE_GROUP => 0
1595 ]
1596 ];
6399c7ef 1597
8e91aaab
JD
1598 $countsrs = $DB->get_recordset_sql($sql, $params);
1599 foreach ($countsrs as $key => $val) {
1600 if (!empty($val->itemtype)) {
c296c48f 1601 $counts['favourites'] += $val->count;
8e91aaab
JD
1602 continue;
1603 }
1604 $counts['types'][$val->type] = $val->count;
6399c7ef 1605 }
8e91aaab 1606 $countsrs->close();
6399c7ef 1607
8e91aaab 1608 return $counts;
6399c7ef
RW
1609 }
1610
79f6c36c 1611 /**
74ad60bf 1612 * Marks all messages being sent to a user in a particular conversation.
79f6c36c 1613 *
74ad60bf 1614 * If $conversationdid is null then it marks all messages as read sent to $userid.
79f6c36c 1615 *
74ad60bf
MN
1616 * @param int $userid
1617 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
79f6c36c 1618 */
74ad60bf 1619 public static function mark_all_messages_as_read($userid, $conversationid = null) {
79f6c36c
MN
1620 global $DB;
1621
883ce421
MN
1622 $messagesql = "SELECT m.*
1623 FROM {messages} m
1624 INNER JOIN {message_conversations} mc
1625 ON mc.id = m.conversationid
1626 INNER JOIN {message_conversation_members} mcm
1627 ON mcm.conversationid = mc.id
5aac33c7
MN
1628 LEFT JOIN {message_user_actions} mua
1629 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1630 WHERE mua.id is NULL
1631 AND mcm.userid = ?
74ad60bf 1632 AND m.useridfrom != ?";
5aac33c7
MN
1633 $messageparams = [];
1634 $messageparams[] = $userid;
1635 $messageparams[] = self::MESSAGE_ACTION_READ;
74ad60bf
MN
1636 $messageparams[] = $userid;
1637 $messageparams[] = $userid;
1638 if (!is_null($conversationid)) {
1639 $messagesql .= " AND mc.id = ?";
1640 $messageparams[] = $conversationid;
79f6c36c
MN
1641 }
1642
74ad60bf
MN
1643 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
1644 foreach ($messages as $message) {
1645 self::mark_message_as_read($userid, $message);
1646 }
1647 $messages->close();
1648 }
1649
1650 /**
1651 * Marks all notifications being sent from one user to another user as read.
1652 *
1653 * If the from user is null then it marks all notifications as read sent to the to user.
1654 *
1655 * @param int $touserid the id of the message recipient
1656 * @param int|null $fromuserid the id of the message sender, null if all messages
1657 * @return void
1658 */
1659 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
1660 global $DB;
1661
883ce421
MN
1662 $notificationsql = "SELECT n.*
1663 FROM {notifications} n
74ad60bf
MN
1664 WHERE useridto = ?
1665 AND timeread is NULL";
883ce421 1666 $notificationsparams = [$touserid];
79f6c36c 1667 if (!empty($fromuserid)) {
883ce421
MN
1668 $notificationsql .= " AND useridfrom = ?";
1669 $notificationsparams[] = $fromuserid;
79f6c36c
MN
1670 }
1671
74ad60bf
MN
1672 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
1673 foreach ($notifications as $notification) {
1674 self::mark_notification_as_read($notification);
79f6c36c 1675 }
74ad60bf
MN
1676 $notifications->close();
1677 }
79f6c36c 1678
74ad60bf
MN
1679 /**
1680 * Marks ALL messages being sent from $fromuserid to $touserid as read.
1681 *
1682 * Can be filtered by type.
1683 *
1684 * @deprecated since 3.5
1685 * @param int $touserid the id of the message recipient
1686 * @param int $fromuserid the id of the message sender
1687 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
1688 * @return void
1689 */
1690 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
1691 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
1692 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
1693 DEBUG_DEVELOPER);
1694
1695 $type = strtolower($type);
1696
1697 $conversationid = null;
1698 $ignoremessages = false;
1699 if (!empty($fromuserid)) {
99248f61 1700 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
74ad60bf
MN
1701 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
1702 $ignoremessages = true;
1703 }
79f6c36c
MN
1704 }
1705
74ad60bf
MN
1706 if (!empty($type)) {
1707 if ($type == MESSAGE_TYPE_NOTIFICATION) {
99248f61 1708 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf
MN
1709 } else if ($type == MESSAGE_TYPE_MESSAGE) {
1710 if (!$ignoremessages) {
99248f61 1711 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf
MN
1712 }
1713 }
1714 } else { // We want both.
99248f61 1715 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf 1716 if (!$ignoremessages) {
99248f61 1717 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf 1718 }
883ce421 1719 }
79f6c36c
MN
1720 }
1721
79f6c36c
MN
1722 /**
1723 * Returns message preferences.
1724 *
1725 * @param array $processors
1726 * @param array $providers
1727 * @param \stdClass $user
1728 * @return \stdClass
1729 * @since 3.2
1730 */
1731 public static function get_all_message_preferences($processors, $providers, $user) {
1732 $preferences = helper::get_providers_preferences($providers, $user->id);
1733 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
1734
1735 // For every processors put its options on the form (need to get function from processor's lib.php).
1736 foreach ($processors as $processor) {
1737 $processor->object->load_data($preferences, $user->id);
1738 }
1739
1740 // Load general messaging preferences.
f7dfa9ba 1741 $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
79f6c36c
MN
1742 $preferences->mailformat = $user->mailformat;
1743 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
1744
1745 return $preferences;
1746 }
5b0769db
MN
1747
1748 /**
1749 * Count the number of users blocked by a user.
1750 *
1751 * @param \stdClass $user The user object
1752 * @return int the number of blocked users
1753 */
1754 public static function count_blocked_users($user = null) {
1755 global $USER, $DB;
1756
1757 if (empty($user)) {
1758 $user = $USER;
1759 }
1760
f219eac7
MN
1761 $sql = "SELECT count(mub.id)
1762 FROM {message_users_blocked} mub
1763 WHERE mub.userid = :userid";
5b0769db
MN
1764 return $DB->count_records_sql($sql, array('userid' => $user->id));
1765 }
1766
1767 /**
1768 * Determines if a user is permitted to send another user a private message.
1769 * If no sender is provided then it defaults to the logged in user.
1770 *
1771 * @param \stdClass $recipient The user object.
1772 * @param \stdClass|null $sender The user object.
1773 * @return bool true if user is permitted, false otherwise.
1774 */
1775 public static function can_post_message($recipient, $sender = null) {
1776 global $USER;
1777
1778 if (is_null($sender)) {
1779 // The message is from the logged in user, unless otherwise specified.
1780 $sender = $USER;
1781 }
1782
7983fb83
SA
1783 $systemcontext = \context_system::instance();
1784 if (!has_capability('moodle/site:sendmessage', $systemcontext, $sender)) {
5b0769db
MN
1785 return false;
1786 }
1787
7983fb83 1788 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender->id)) {
c886e2c9
MN
1789 return true;
1790 }
1791
7983fb83 1792 // Check if the recipient can be messaged by the sender.
9f82758c 1793 return (self::can_contact_user($recipient->id, $sender->id));
5b0769db
MN
1794 }
1795
8e3bf150
JD
1796 /**
1797 * Determines if a user is permitted to send a message to a given conversation.
1798 * If no sender is provided then it defaults to the logged in user.
1799 *
1800 * @param int $userid the id of the user on which the checks will be applied.
1801 * @param int $conversationid the id of the conversation we wish to check.
1802 * @return bool true if the user can send a message to the conversation, false otherwise.
1803 * @throws \moodle_exception
1804 */
1805 public static function can_send_message_to_conversation(int $userid, int $conversationid) : bool {
1806 global $DB;
1807
1808 $systemcontext = \context_system::instance();
1809 if (!has_capability('moodle/site:sendmessage', $systemcontext, $userid)) {
1810 return false;
1811 }
1812
1813 if (!self::is_user_in_conversation($userid, $conversationid)) {
1814 return false;
1815 }
1816
1817 // User can post messages and is in the conversation, but we need to check the conversation type to
1818 // know whether or not to check the user privacy settings via can_contact_user().
1819 $conversation = $DB->get_record('message_conversations', ['id' => $conversationid], '*', MUST_EXIST);
1820 if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
1821 return true;
1822 } else if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1823 // Get the other user in the conversation.
1824 $members = self::get_conversation_members($userid, $conversationid);
1825 $otheruser = array_filter($members, function($member) use($userid) {
1826 return $member->id != $userid;
1827 });
1828 $otheruser = reset($otheruser);
1829
9f82758c 1830 return self::can_contact_user($otheruser->id, $userid);
8e3bf150
JD
1831 } else {
1832 throw new \moodle_exception("Invalid conversation type '$conversation->type'.");
1833 }
1834 }
1835
52f9cf20
JD
1836 /**
1837 * Send a message from a user to a conversation.
1838 *
1839 * This method will create the basic eventdata and delegate to message creation to message_send.
1840 * The message_send() method is responsible for event data that is specific to each recipient.
1841 *
1842 * @param int $userid the sender id.
1843 * @param int $conversationid the conversation id.
1844 * @param string $message the message to send.
1845 * @param int $format the format of the message to send.
1846 * @return \stdClass the message created.
1847 * @throws \coding_exception
1848 * @throws \moodle_exception if the user is not permitted to send a message to the conversation.
1849 */
1850 public static function send_message_to_conversation(int $userid, int $conversationid, string $message,
1851 int $format) : \stdClass {
1852 global $DB;
1853
1854 if (!self::can_send_message_to_conversation($userid, $conversationid)) {
1855 throw new \moodle_exception("User $userid cannot send a message to conversation $conversationid");
1856 }
1857
1858 $eventdata = new \core\message\message();
1859 $eventdata->courseid = 1;
1860 $eventdata->component = 'moodle';
1861 $eventdata->name = 'instantmessage';
1862 $eventdata->userfrom = $userid;
1863 $eventdata->convid = $conversationid;
1864
1865 if ($format == FORMAT_HTML) {
1866 $eventdata->fullmessagehtml = $message;
1867 // Some message processors may revert to sending plain text even if html is supplied,
1868 // so we keep both plain and html versions if we're intending to send html.
1869 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
1870 } else {
1871 $eventdata->fullmessage = $message;
1872 $eventdata->fullmessagehtml = '';
1873 }
1874
1875 $eventdata->fullmessageformat = $format;
1876 $eventdata->smallmessage = $message; // Store the message unfiltered. Clean up on output.
1877
1878 $eventdata->timecreated = time();
1879 $eventdata->notification = 0;
1880 $messageid = message_send($eventdata);
1881
1882 $messagerecord = $DB->get_record('messages', ['id' => $messageid], 'id, useridfrom, fullmessage, timecreated');
1883 $message = (object) [
1884 'id' => $messagerecord->id,
1885 'useridfrom' => $messagerecord->useridfrom,
1886 'text' => $messagerecord->fullmessage,
1887 'timecreated' => $messagerecord->timecreated
1888 ];
1889 return $message;
5b0769db
MN
1890 }
1891
f7dfa9ba
SA
1892 /**
1893 * Get the messaging preference for a user.
1894 * If the user has not any messaging privacy preference:
1895 * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
1896 * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
1897 *
1898 * @param int $userid The user identifier.
1899 * @return int The default messaging preference.
1900 */
1901 public static function get_user_privacy_messaging_preference(int $userid) : int {
d3d95d5d 1902 global $CFG, $USER;
f7dfa9ba
SA
1903
1904 // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
1905 // otherwise, the default value will be "My contacts and anyone in my courses".
1906 if (empty($CFG->messagingallusers)) {
1907 $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
1908 } else {
1909 $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
1910 }
d3d95d5d
RW
1911 if ($userid == $USER->id) {
1912 $user = $USER;
1913 } else {
1914 $user = $userid;
1915 }
1916 $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $user);
f7dfa9ba
SA
1917
1918 // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
1919 // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1920 if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
1921 $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
1922 }
1923
1924 return $privacypreference;
1925 }
1926
5b0769db
MN
1927 /**
1928 * Checks if the recipient is allowing messages from users that aren't a
1929 * contact. If not then it checks to make sure the sender is in the
1930 * recipient's contacts.
1931 *
e5eba802 1932 * @deprecated since 3.6
5b0769db
MN
1933 * @param \stdClass $recipient The user object.
1934 * @param \stdClass|null $sender The user object.
1935 * @return bool true if $sender is blocked, false otherwise.
1936 */
1937 public static function is_user_non_contact_blocked($recipient, $sender = null) {
e5eba802
SA
1938 debugging('\core_message\api::is_user_non_contact_blocked() is deprecated', DEBUG_DEVELOPER);
1939
f7dfa9ba 1940 global $USER, $CFG;
5b0769db
MN
1941
1942 if (is_null($sender)) {
1943 // The message is from the logged in user, unless otherwise specified.
1944 $sender = $USER;
1945 }
1946
f7dfa9ba
SA
1947 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1948 switch ($privacypreference) {
1949 case self::MESSAGE_PRIVACY_SITE:
1950 if (!empty($CFG->messagingallusers)) {
1951 // Users can be messaged without being contacts or members of the same course.
1952 break;
1953 }
1954 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1955 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1956 case self::MESSAGE_PRIVACY_COURSEMEMBER:
1957 // Confirm the sender and the recipient are both members of the same course.
1958 if (enrol_sharing_course($recipient, $sender)) {
1959 // All good, the recipient and the sender are members of the same course.
1960 return false;
1961 }
1962 case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1963 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1964 return !self::is_contact($sender->id, $recipient->id);
5b0769db
MN
1965 }
1966
1967 return false;
1968 }
1969
1970 /**
1971 * Checks if the recipient has specifically blocked the sending user.
1972 *
1973 * Note: This function will always return false if the sender has the
1974 * readallmessages capability at the system context level.
1975 *
c886e2c9 1976 * @deprecated since 3.6
26dca05d
JP
1977 * @param int $recipientid User ID of the recipient.
1978 * @param int $senderid User ID of the sender.
5b0769db
MN
1979 * @return bool true if $sender is blocked, false otherwise.
1980 */
26dca05d 1981 public static function is_user_blocked($recipientid, $senderid = null) {
c886e2c9
MN
1982 debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1983 DEBUG_DEVELOPER);
1984
1985 global $USER;
5b0769db 1986
26dca05d 1987 if (is_null($senderid)) {
5b0769db 1988 // The message is from the logged in user, unless otherwise specified.
26dca05d 1989 $senderid = $USER->id;
5b0769db
MN
1990 }
1991
1992 $systemcontext = \context_system::instance();
26dca05d 1993 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
5b0769db
MN
1994 return false;
1995 }
1996
f219eac7 1997 if (self::is_blocked($recipientid, $senderid)) {
26dca05d 1998 return true;
5b0769db
MN
1999 }
2000
2001 return false;
2002 }
20ab51fd
AA
2003
2004 /**
2005 * Get specified message processor, validate corresponding plugin existence and
2006 * system configuration.
2007 *
2008 * @param string $name Name of the processor.
2009 * @param bool $ready only return ready-to-use processors.
2010 * @return mixed $processor if processor present else empty array.
2011 * @since Moodle 3.2
2012 */
2013 public static function get_message_processor($name, $ready = false) {
2014 global $DB, $CFG;
2015
2016 $processor = $DB->get_record('message_processors', array('name' => $name));
2017 if (empty($processor)) {
2018 // Processor not found, return.
2019 return array();
2020 }
2021
2022 $processor = self::get_processed_processor_object($processor);
2023 if ($ready) {
2024 if ($processor->enabled && $processor->configured) {
2025 return $processor;
2026 } else {
2027 return array();
2028 }
2029 } else {
2030 return $processor;
2031 }
2032 }
2033
2034 /**
2035 * Returns weather a given processor is enabled or not.
2036 * Note:- This doesn't check if the processor is configured or not.
2037 *
2038 * @param string $name Name of the processor
2039 * @return bool
2040 */
2041 public static function is_processor_enabled($name) {
2042
2043 $cache = \cache::make('core', 'message_processors_enabled');
2044 $status = $cache->get($name);
2045
2046 if ($status === false) {
2047 $processor = self::get_message_processor($name);
2048 if (!empty($processor)) {
2049 $cache->set($name, $processor->enabled);
2050 return $processor->enabled;
2051 } else {
2052 return false;
2053 }
2054 }
2055
2056 return $status;
2057 }
2058
2059 /**
2060 * Set status of a processor.
2061 *
2062 * @param \stdClass $processor processor record.
2063 * @param 0|1 $enabled 0 or 1 to set the processor status.
2064 * @return bool
2065 * @since Moodle 3.2
2066 */
2067 public static function update_processor_status($processor, $enabled) {
2068 global $DB;
2069 $cache = \cache::make('core', 'message_processors_enabled');
2070 $cache->delete($processor->name);
2071 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
2072 }
2073
2074 /**
2075 * Given a processor object, loads information about it's settings and configurations.
2076 * This is not a public api, instead use @see \core_message\api::get_message_processor()
2077 * or @see \get_message_processors()
2078 *
2079 * @param \stdClass $processor processor object
2080 * @return \stdClass processed processor object
2081 * @since Moodle 3.2
2082 */
2083 public static function get_processed_processor_object(\stdClass $processor) {
2084 global $CFG;
2085
2086 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2087 if (is_readable($processorfile)) {
2088 include_once($processorfile);
2089 $processclass = 'message_output_' . $processor->name;
2090 if (class_exists($processclass)) {
2091 $pclass = new $processclass();
2092 $processor->object = $pclass;
2093 $processor->configured = 0;
2094 if ($pclass->is_system_configured()) {
2095 $processor->configured = 1;
2096 }
2097 $processor->hassettings = 0;
2098 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2099 $processor->hassettings = 1;
2100 }
2101 $processor->available = 1;
2102 } else {
2103 print_error('errorcallingprocessor', 'message');
2104 }
2105 } else {
2106 $processor->available = 0;
2107 }
2108 return $processor;
2109 }
883ce421
MN
2110
2111 /**
2112 * Retrieve users blocked by $user1
2113 *
2114 * @param int $userid The user id of the user whos blocked users we are returning
2115 * @return array the users blocked
2116 */
2117 public static function get_blocked_users($userid) {
2118 global $DB;
2119
2120 $userfields = \user_picture::fields('u', array('lastaccess'));
2121 $blockeduserssql = "SELECT $userfields
f219eac7 2122 FROM {message_users_blocked} mub
883ce421 2123 INNER JOIN {user} u
f219eac7 2124 ON u.id = mub.blockeduserid
883ce421 2125 WHERE u.deleted = 0
f219eac7 2126 AND mub.userid = ?
883ce421
MN
2127 GROUP BY $userfields
2128 ORDER BY u.firstname ASC";
2129 return $DB->get_records_sql($blockeduserssql, [$userid]);
2130 }
2131
2132 /**
2133 * Mark a single message as read.
2134 *
2135 * @param int $userid The user id who marked the message as read
548936a6 2136 * @param \stdClass $message The message
883ce421
MN
2137 * @param int|null $timeread The time the message was marked as read, if null will default to time()
2138 */
548936a6 2139 public static function mark_message_as_read($userid, $message, $timeread = null) {
883ce421
MN
2140 global $DB;
2141
2142 if (is_null($timeread)) {
2143 $timeread = time();
2144 }
2145
5aac33c7
MN
2146 $mua = new \stdClass();
2147 $mua->userid = $userid;
2148 $mua->messageid = $message->id;
2149 $mua->action = self::MESSAGE_ACTION_READ;
2150 $mua->timecreated = $timeread;
2151 $mua->id = $DB->insert_record('message_user_actions', $mua);
2152
2153 // Get the context for the user who received the message.
2154 $context = \context_user::instance($userid, IGNORE_MISSING);
2155 // If the user no longer exists the context value will be false, in this case use the system context.
2156 if ($context === false) {
2157 $context = \context_system::instance();
883ce421 2158 }
5aac33c7
MN
2159
2160 // Trigger event for reading a message.
2161 $event = \core\event\message_viewed::create(array(
2162 'objectid' => $mua->id,
2163 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
2164 'context' => $context,
2165 'relateduserid' => $message->useridfrom,
2166 'other' => array(
2167 'messageid' => $message->id
2168 )
2169 ));
2170 $event->trigger();
883ce421
MN
2171 }
2172
2173 /**
2174 * Mark a single notification as read.
2175 *
548936a6 2176 * @param \stdClass $notification The notification
883ce421
MN
2177 * @param int|null $timeread The time the message was marked as read, if null will default to time()
2178 */
548936a6 2179 public static function mark_notification_as_read($notification, $timeread = null) {
883ce421
MN
2180 global $DB;
2181
2182 if (is_null($timeread)) {
2183 $timeread = time();
2184 }
2185
883ce421
MN
2186 if (is_null($notification->timeread)) {
2187 $updatenotification = new \stdClass();
2188 $updatenotification->id = $notification->id;
2189 $updatenotification->timeread = $timeread;
2190
2191 $DB->update_record('notifications', $updatenotification);
376a79c2
MN
2192
2193 // Trigger event for reading a notification.
2194 \core\event\notification_viewed::create_from_ids(
2195 $notification->useridfrom,
2196 $notification->useridto,
2197 $notification->id
2198 )->trigger();
883ce421
MN
2199 }
2200 }
2201
2202 /**
2203 * Checks if a user can delete a message.
2204 *
2205 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
2206 * but will still seem as if it was by the user)
2207 * @param int $messageid The message id
2208 * @return bool Returns true if a user can delete the message, false otherwise.
2209 */
2210 public static function can_delete_message($userid, $messageid) {
2211 global $DB, $USER;
2212
08cb8a34
MN
2213 $systemcontext = \context_system::instance();
2214
2215 $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
2216
2217 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
2218 return true;
883ce421
MN
2219 }
2220
08cb8a34
MN
2221 if (!self::is_user_in_conversation($userid, $conversationid)) {
2222 return false;
2223 }
883ce421 2224
08cb8a34
MN
2225 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
2226 $USER->id == $userid) {
883ce421
MN
2227 return true;
2228 }
2229
2230 return false;
2231 }
2232
2233 /**
2234 * Deletes a message.
2235 *
2236 * This function does not verify any permissions.
2237 *
2238 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
2239 * but will still seem as if it was by the user)
2240 * @param int $messageid The message id
2241 * @return bool
2242 */
2243 public static function delete_message($userid, $messageid) {
14de10c4 2244 global $DB, $USER;
883ce421 2245
14de10c4
MN
2246 if (!$DB->record_exists('messages', ['id' => $messageid])) {
2247 return false;
2248 }
883ce421
MN
2249
2250 // Check if the user has already deleted this message.
2251 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
2252 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
2253 $mua = new \stdClass();
2254 $mua->userid = $userid;
2255 $mua->messageid = $messageid;
2256 $mua->action = self::MESSAGE_ACTION_DELETED;
2257 $mua->timecreated = time();
2258 $mua->id = $DB->insert_record('message_user_actions', $mua);
2259
2260 // Trigger event for deleting a message.
14de10c4
MN
2261 \core\event\message_deleted::create_from_ids($userid, $USER->id,
2262 $messageid, $mua->id)->trigger();
883ce421
MN
2263
2264 return true;
2265 }
2266
2267 return false;
2268 }
2269
2270 /**
2271 * Returns the conversation between two users.
2272 *
b2cd17e6 2273 * @param array $userids
883ce421
MN
2274 * @return int|bool The id of the conversation, false if not found
2275 */
b2cd17e6 2276 public static function get_conversation_between_users(array $userids) {
883ce421
MN
2277 global $DB;
2278
0866b336
RW
2279 $conversations = self::get_individual_conversations_between_users([$userids]);
2280 $conversation = $conversations[0];
883ce421 2281
0866b336 2282 if ($conversation) {
883ce421
MN
2283 return $conversation->id;
2284 }
2285
2286 return false;
2287 }
2288
0866b336
RW
2289 /**
2290 * Returns the conversations between sets of users.
2291 *
2292 * The returned array of results will be in the same order as the requested
2293 * arguments, null will be returned if there is no conversation for that user
2294 * pair.
2295 *
2296 * For example:
2297 * If we have 6 users with ids 1, 2, 3, 4, 5, 6 where only 2 conversations
2298 * exist. One between 1 and 2 and another between 5 and 6.
2299 *
2300 * Then if we call:
2301 * $conversations = get_individual_conversations_between_users([[1,2], [3,4], [5,6]]);
2302 *
2303 * The conversations array will look like:
2304 * [<conv_record>, null, <conv_record>];
2305 *
2306 * Where null is returned for the pairing of [3, 4] since no record exists.
2307 *
2308 * @param array $useridsets An array of arrays where the inner array is the set of user ids
2309 * @return stdClass[] Array of conversation records
2310 */
2311 public static function get_individual_conversations_between_users(array $useridsets) : array {
2312 global $DB;
2313
2314 if (empty($useridsets)) {
2315 return [];
2316 }
2317
2318 $hashes = array_map(function($userids) {
2319 return helper::get_conversation_hash($userids);
2320 }, $useridsets);
2321
2322 list($inorequalsql, $params) = $DB->get_in_or_equal($hashes);
2323 array_unshift($params, self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL);
2324 $where = "type = ? AND convhash ${inorequalsql}";
2325 $conversations = array_fill(0, count($hashes), null);
2326 $records = $DB->get_records_select('message_conversations', $where, $params);
2327
2328 foreach (array_values($records) as $record) {
2329 $index = array_search($record->convhash, $hashes);
2330 if ($index !== false) {
2331 $conversations[$index] = $record;
2332 }
2333 }
2334
2335 return $conversations;
2336 }
2337
883ce421
MN
2338 /**
2339 * Creates a conversation between two users.
2340 *
a66ae849 2341 * @deprecated since 3.6
b2cd17e6 2342 * @param array $userids
883ce421
MN
2343 * @return int The id of the conversation
2344 */
b2cd17e6 2345 public static function create_conversation_between_users(array $userids) {
a66ae849
MN
2346 debugging('\core_message\api::create_conversation_between_users is deprecated, please use ' .
2347 '\core_message\api::create_conversation instead.', DEBUG_DEVELOPER);
2348
f2ac0a3e
MN
2349 // This method was always used for individual conversations.
2350 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
2351
2352 return $conversation->id;
2353 }
2354
2355 /**
2356 * Creates a conversation with selected users and messages.
2357 *
2358 * @param int $type The type of conversation
2359 * @param int[] $userids The array of users to add to the conversation
76540bec
MN
2360 * @param string|null $name The name of the conversation
2361 * @param int $enabled Determines if the conversation is created enabled or disabled
2362 * @param string|null $component Defines the Moodle component which the conversation belongs to, if any
2363 * @param string|null $itemtype Defines the type of the component
2364 * @param int|null $itemid The id of the component
2365 * @param int|null $contextid The id of the context
f2ac0a3e
MN
2366 * @return \stdClass
2367 */
76540bec
MN
2368 public static function create_conversation(int $type, array $userids, string $name = null,
2369 int $enabled = self::MESSAGE_CONVERSATION_ENABLED, string $component = null,
2370 string $itemtype = null, int $itemid = null, int $contextid = null) {
2371
883ce421
MN
2372 global $DB;
2373
869eac82
MN
2374 $validtypes = [
2375 self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2376 self::MESSAGE_CONVERSATION_TYPE_GROUP
2377 ];
2378
2379 if (!in_array($type, $validtypes)) {
2380 throw new \moodle_exception('An invalid conversation type was specified.');
2381 }
2382
f2ac0a3e
MN
2383 // Sanity check.
2384 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
2385 if (count($userids) > 2) {
2386 throw new \moodle_exception('An individual conversation can not have more than two users.');
2387 }
2388 }
2389
883ce421 2390 $conversation = new \stdClass();
f2ac0a3e
MN
2391 $conversation->type = $type;
2392 $conversation->name = $name;
2393 $conversation->convhash = null;
2394 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
2395 $conversation->convhash = helper::get_conversation_hash($userids);
2396 }
76540bec
MN
2397 $conversation->component = $component;
2398 $conversation->itemtype = $itemtype;
2399 $conversation->itemid = $itemid;
2400 $conversation->contextid = $contextid;
2401 $conversation->enabled = $enabled;
883ce421 2402 $conversation->timecreated = time();
76540bec 2403 $conversation->timemodified = $conversation->timecreated;
883ce421
MN
2404 $conversation->id = $DB->insert_record('message_conversations', $conversation);
2405
f2ac0a3e
MN
2406 // Add users to this conversation.
2407 $arrmembers = [];
b2cd17e6
MN
2408 foreach ($userids as $userid) {
2409 $member = new \stdClass();
2410 $member->conversationid = $conversation->id;
2411 $member->userid = $userid;
2412 $member->timecreated = time();
f2ac0a3e
MN
2413 $member->id = $DB->insert_record('message_conversation_members', $member);
2414
2415 $arrmembers[] = $member;
b2cd17e6 2416 }
883ce421 2417
f2ac0a3e
MN
2418 $conversation->members = $arrmembers;
2419
2420 return $conversation;
883ce421 2421 }
0b3eadcd 2422
e66b915c
MN
2423 /**
2424 * Checks if a user can create a group conversation.
2425 *
2426 * @param int $userid The id of the user attempting to create the conversation
2427 * @param \context $context The context they are creating the conversation from, most likely course context
2428 * @return bool
2429 */
2430 public static function can_create_group_conversation(int $userid, \context $context) : bool {
2431 global $CFG;
2432
2433 // If we can't message at all, then we can't create a conversation.
2434 if (empty($CFG->messaging)) {
2435 return false;
2436 }
2437
2438 // We need to check they have the capability to create the conversation.
2439 return has_capability('moodle/course:creategroupconversations', $context, $userid);
883ce421 2440 }
0b3eadcd 2441
0d203bbf
MN
2442 /**
2443 * Checks if a user can create a contact request.
2444 *
2445 * @param int $userid The id of the user who is creating the contact request
2446 * @param int $requesteduserid The id of the user being requested
2447 * @return bool
2448 */
2449 public static function can_create_contact(int $userid, int $requesteduserid) : bool {
2450 global $CFG;
2451
2452 // If we can't message at all, then we can't create a contact.
2453 if (empty($CFG->messaging)) {
2454 return false;
2455 }
2456
2457 // If we can message anyone on the site then we can create a contact.
2458 if ($CFG->messagingallusers) {
2459 return true;
2460 }
2461
2462 // We need to check if they are in the same course.
2463 return enrol_sharing_course($userid, $requesteduserid);
2464 }
2465
0b3eadcd
MN
2466 /**
2467 * Handles creating a contact request.
2468 *
2469 * @param int $userid The id of the user who is creating the contact request
2470 * @param int $requesteduserid The id of the user being requested
0866b336 2471 * @return \stdClass the request
0b3eadcd 2472 */
0866b336 2473 public static function create_contact_request(int $userid, int $requesteduserid) : \stdClass {
0b3eadcd
MN
2474 global $DB;
2475
2476 $request = new \stdClass();
2477 $request->userid = $userid;
2478 $request->requesteduserid = $requesteduserid;
2479 $request->timecreated = time();
2480
0866b336
RW
2481 $request->id = $DB->insert_record('message_contact_requests', $request);
2482
2483 return $request;
0b3eadcd
MN
2484 }
2485
2486
2487 /**
2488 * Handles confirming a contact request.
2489 *
2490 * @param int $userid The id of the user who created the contact request
2491 * @param int $requesteduserid The id of the user confirming the request
2492 */
2493 public static function confirm_contact_request(int $userid, int $requesteduserid) {
2494 global $DB;
2495
2496 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2497 'requesteduserid' => $requesteduserid])) {
2498 self::add_contact($userid, $requesteduserid);
2499
2500 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2501 }
2502 }
2503
2504 /**
2505 * Handles declining a contact request.
2506 *
2507 * @param int $userid The id of the user who created the contact request
2508 * @param int $requesteduserid The id of the user declining the request
2509 */
2510 public static function decline_contact_request(int $userid, int $requesteduserid) {
2511 global $DB;
2512
2513 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2514 'requesteduserid' => $requesteduserid])) {
2515 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2516 }
2517 }
2518
2519 /**
2520 * Handles returning the contact requests for a user.
2521 *
2522 * This also includes the user data necessary to display information
2523 * about the user.
2524 *
2525 * It will not include blocked users.
2526 *
2527 * @param int $userid
accd6482
MN
2528 * @param int $limitfrom
2529 * @param int $limitnum
0b3eadcd
MN
2530 * @return array The list of contact requests
2531 */
accd6482 2532 public static function get_contact_requests(int $userid, int $limitfrom = 0, int $limitnum = 0) : array {
0b3eadcd
MN
2533 global $DB;
2534
daa33803
MN
2535 $sql = "SELECT mcr.userid
2536 FROM {message_contact_requests} mcr
0b3eadcd 2537 LEFT JOIN {message_users_blocked} mub
daa33803 2538 ON (mub.userid = ? AND mub.blockeduserid = mcr.userid)
0b3eadcd 2539 WHERE mcr.requesteduserid = ?
0b3eadcd 2540 AND mub.id is NULL
accd6482
MN
2541 ORDER BY mcr.timecreated ASC";
2542 if ($contactrequests = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
daa33803
MN
2543 $userids = array_keys($contactrequests);
2544 return helper::get_member_info($userid, $userids);
2545 }
0b3eadcd 2546
daa33803 2547 return [];
0b3eadcd
MN
2548 }
2549
0866b336 2550 /**
720cc993 2551 * Returns the number of contact requests the user has received.
0866b336 2552 *
720cc993 2553 * @param int $userid The ID of the user we want to return the number of received contact requests for
0866b336
RW
2554 * @return int The count
2555 */
720cc993 2556 public static function get_received_contact_requests_count(int $userid) : int {
0866b336 2557 global $DB;
e492a554
JD
2558 $sql = "SELECT COUNT(mcr.id)
2559 FROM {message_contact_requests} mcr
2560 LEFT JOIN {message_users_blocked} mub
2561 ON mub.userid = mcr.requesteduserid AND mub.blockeduserid = mcr.userid
2562 WHERE mcr.requesteduserid = :requesteduserid
2563 AND mub.id IS NULL";
2564 $params = ['requesteduserid' => $userid];
2565 return $DB->count_records_sql($sql, $params);
0866b336
RW
2566 }
2567
0b3eadcd
MN
2568 /**
2569 * Handles adding a contact.
2570 *
2571 * @param int $userid The id of the user who requested to be a contact
2572 * @param int $contactid The id of the contact
2573 */
2574 public static function add_contact(int $userid, int $contactid) {
2575 global $DB;
2576
2577 $messagecontact = new \stdClass();
2578 $messagecontact->userid = $userid;
2579 $messagecontact->contactid = $contactid;
2580 $messagecontact->timecreated = time();
2581 $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
2582
2583 $eventparams = [
2584 'objectid' => $messagecontact->id,
2585 'userid' => $userid,
2586 'relateduserid' => $contactid,
2587 'context' => \context_user::instance($userid)
2588 ];
2589 $event = \core\event\message_contact_added::create($eventparams);
2590 $event->add_record_snapshot('message_contacts', $messagecontact);
2591 $event->trigger();
2592 }
2593
2594 /**
2595 * Handles removing a contact.
2596 *
2597 * @param int $userid The id of the user who is removing a user as a contact
2598 * @param int $contactid The id of the user to be removed as a contact
2599 */
2600 public static function remove_contact(int $userid, int $contactid) {
2601 global $DB;
2602
2603 if ($contact = self::get_contact($userid, $contactid)) {
2604 $DB->delete_records('message_contacts', ['id' => $contact->id]);
2605
2606 $event = \core\event\message_contact_removed::create(array(
2607 'objectid' => $contact->id,
2608 'userid' => $userid,
2609 'relateduserid' => $contactid,
2610 'context' => \context_user::instance($userid)
2611 ));
2612 $event->add_record_snapshot('message_contacts', $contact);
2613 $event->trigger();
2614 }
2615 }
2616
2617 /**
2618 * Handles blocking a user.
2619 *
2620 * @param int $userid The id of the user who is blocking
2621 * @param int $usertoblockid The id of the user being blocked
2622 */
2623 public static function block_user(int $userid, int $usertoblockid) {
2624 global $DB;
2625
2626 $blocked = new \stdClass();
2627 $blocked->userid = $userid;
2628 $blocked->blockeduserid = $usertoblockid;
2629 $blocked->timecreated = time();
2630 $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
2631
2632 // Trigger event for blocking a contact.
2633 $event = \core\event\message_user_blocked::create(array(
2634 'objectid' => $blocked->id,
2635 'userid' => $userid,
2636 'relateduserid' => $usertoblockid,
2637 'context' => \context_user::instance($userid)
2638 ));
2639 $event->add_record_snapshot('message_users_blocked', $blocked);
2640 $event->trigger();
2641 }
2642
2643 /**
2644 * Handles unblocking a user.
2645 *
2646 * @param int $userid The id of the user who is unblocking
2647 * @param int $usertounblockid The id of the user being unblocked
2648 */
2649 public static function unblock_user(int $userid, int $usertounblockid) {
2650 global $DB;
2651
2652 if ($blockeduser = $DB->get_record('message_users_blocked',
2653 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
2654 $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
2655
2656 // Trigger event for unblocking a contact.
2657 $event = \core\event\message_user_unblocked::create(array(
2658 'objectid' => $blockeduser->id,
2659 'userid' => $userid,
2660 'relateduserid' => $usertounblockid,
2661 'context' => \context_user::instance($userid)
2662 ));
2663 $event->add_record_snapshot('message_users_blocked', $blockeduser);
2664 $event->trigger();
2665 }
2666 }
2667
2668 /**
2669 * Checks if users are already contacts.
2670 *
2671 * @param int $userid The id of one of the users
2672 * @param int $contactid The id of the other user
2673 * @return bool Returns true if they are a contact, false otherwise
2674 */
2675 public static function is_contact(int $userid, int $contactid) : bool {
2676 global $DB;
2677
2678 $sql = "SELECT id
2679 FROM {message_contacts} mc
2680 WHERE (mc.userid = ? AND mc.contactid = ?)
2681 OR (mc.userid = ? AND mc.contactid = ?)";
2682 return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
2683 }
2684
2685 /**
2686 * Returns the row in the database table message_contacts that represents the contact between two people.
2687 *
2688 * @param int $userid The id of one of the users
2689 * @param int $contactid The id of the other user
2690 * @return mixed A fieldset object containing the record, false otherwise
2691 */
2692 public static function get_contact(int $userid, int $contactid) {
2693 global $DB;
2694
2695 $sql = "SELECT mc.*
2696 FROM {message_contacts} mc
2697 WHERE (mc.userid = ? AND mc.contactid = ?)
2698 OR (mc.userid = ? AND mc.contactid = ?)";
2699 return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
2700 }
2701
2702 /**
2703 * Checks if a user is already blocked.
2704 *
0b3eadcd
MN
2705 * @param int $userid
2706 * @param int $blockeduserid
2707 * @return bool Returns true if they are a blocked, false otherwise
2708 */
2709 public static function is_blocked(int $userid, int $blockeduserid) : bool {
2710 global $DB;
2711
2712 return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
2713 }
2714
0866b336
RW
2715 /**
2716 * Get contact requests between users.
2717 *
2718 * @param int $userid The id of the user who is creating the contact request
2719 * @param int $requesteduserid The id of the user being requested
2720 * @return \stdClass[]
2721 */
2722 public static function get_contact_requests_between_users(int $userid, int $requesteduserid) : array {
2723 global $DB;
2724
2725 $sql = "SELECT *
2726 FROM {message_contact_requests} mcr
2727 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
2728 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
2729 return $DB->get_records_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
2730 }
2731
0b3eadcd
MN
2732 /**
2733 * Checks if a contact request already exists between users.
2734 *
2735 * @param int $userid The id of the user who is creating the contact request
2736 * @param int $requesteduserid The id of the user being requested
2737 * @return bool Returns true if a contact request exists, false otherwise
2738 */
2739 public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
2740 global $DB;
2741
2742 $sql = "SELECT id
2743 FROM {message_contact_requests} mcr
2744 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
2745 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
2746 return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
2747 }
08cb8a34
MN
2748
2749 /**
2750 * Checks if a user is already in a conversation.
2751 *
2752 * @param int $userid The id of the user we want to check if they are in a group
2753 * @param int $conversationid The id of the conversation
2754 * @return bool Returns true if a contact request exists, false otherwise
2755 */
2756 public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
2757 global $DB;
2758
2759 return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
2760 'userid' => $userid]);
7983fb83
SA
2761 }
2762
2763 /**
2764 * Checks if the sender can message the recipient.
2765 *
9f82758c
JD
2766 * @param int $recipientid
2767 * @param int $senderid
7983fb83
SA
2768 * @return bool true if recipient hasn't blocked sender and sender can contact to recipient, false otherwise.
2769 */
9f82758c
JD
2770 protected static function can_contact_user(int $recipientid, int $senderid) : bool {
2771 if (has_capability('moodle/site:messageanyuser', \context_system::instance(), $senderid)) {
7983fb83
SA
2772 // The sender has the ability to contact any user across the entire site.
2773 return true;
2774 }
2775
2776 // The initial value of $cancontact is null to indicate that a value has not been determined.
2777 $cancontact = null;
2778
9f82758c 2779 if (self::is_blocked($recipientid, $senderid)) {
7983fb83
SA
2780 // The recipient has specifically blocked this sender.
2781 $cancontact = false;
2782 }
2783
2784 $sharedcourses = null;
2785 if (null === $cancontact) {
2786 // There are three user preference options:
2787 // - Site: Allow anyone not explicitly blocked to contact me;
2788 // - Course members: Allow anyone I am in a course with to contact me; and
2789 // - Contacts: Only allow my contacts to contact me.
2790 //
2791 // The Site option is only possible when the messagingallusers site setting is also enabled.
2792
9f82758c 2793 $privacypreference = self::get_user_privacy_messaging_preference($recipientid);
7983fb83
SA
2794 if (self::MESSAGE_PRIVACY_SITE === $privacypreference) {
2795 // The user preference is to allow any user to contact them.
2796 // No need to check anything else.
2797 $cancontact = true;
2798 } else {
2799 // This user only allows their own contacts, and possibly course peers, to contact them.
2800 // If the users are contacts then we can avoid the more expensive shared courses check.
9f82758c 2801 $cancontact = self::is_contact($senderid, $recipientid);
7983fb83
SA
2802
2803 if (!$cancontact && self::MESSAGE_PRIVACY_COURSEMEMBER === $privacypreference) {
2804 // The users are not contacts and the user allows course member messaging.
2805 // Check whether these two users share any course together.
9f82758c 2806 $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
7983fb83
SA
2807 $cancontact = (!empty($sharedcourses));
2808 }
2809 }
2810 }
2811
2812 if (false === $cancontact) {
2813 // At the moment the users cannot contact one another.
2814 // Check whether the messageanyuser capability applies in any of the shared courses.
2815 // This is intended to allow teachers to message students regardless of message settings.
2816
2817 // Note: You cannot use empty($sharedcourses) here because this may be an empty array.
2818 if (null === $sharedcourses) {
9f82758c 2819 $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
7983fb83
SA
2820 }
2821
2822 foreach ($sharedcourses as $course) {
2823 // Note: enrol_get_shared_courses will preload any shared context.
9f82758c 2824 if (has_capability('moodle/site:messageanyuser', \context_course::instance($course->id), $senderid)) {
7983fb83
SA
2825 $cancontact = true;
2826 break;
2827 }
2828 }
2829 }
08cb8a34 2830
7983fb83 2831 return $cancontact;
08cb8a34 2832 }
67b81351 2833
623048af
AA
2834 /**
2835 * Add some new members to an existing conversation.
2836 *
2837 * @param array $userids User ids array to add as members.
2838 * @param int $convid The conversation id. Must exists.
2839 * @throws \dml_missing_record_exception If convid conversation doesn't exist
2840 * @throws \dml_exception If there is a database error
83e3a4fe 2841 * @throws \moodle_exception If trying to add a member(s) to a non-group conversation
623048af
AA
2842 */
2843 public static function add_members_to_conversation(array $userids, int $convid) {
2844 global $DB;
2845
2846 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2847
83e3a4fe
MN
2848 // We can only add members to a group conversation.
2849 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2850 throw new \moodle_exception('You can not add members to a non-group conversation.');
2851 }
2852
623048af
AA
2853 // Be sure we are not trying to add a non existing user to the conversation. Work only with existing users.
2854 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
4abe3d25 2855 $existingusers = $DB->get_fieldset_select('user', 'id', "id $useridcondition", $params);
623048af
AA
2856
2857 // Be sure we are not adding a user is already member of the conversation. Take all the members.
2858 $memberuserids = array_values($DB->get_records_menu(
2859 'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
2860 );
2861
2862 // Work with existing new members.
2863 $members = array();
2864 $newuserids = array_diff($existingusers, $memberuserids);
2865 foreach ($newuserids as $userid) {
2866 $member = new \stdClass();
2867 $member->conversationid = $convid;
2868 $member->userid = $userid;
2869 $member->timecreated = time();
2870 $members[] = $member;
2871 }
2872
623048af 2873 $DB->insert_records('message_conversation_members', $members);
623048af
AA
2874 }
2875
2876 /**
2877 * Remove some members from an existing conversation.
2878 *
2879 * @param array $userids The user ids to remove from conversation members.
2880 * @param int $convid The conversation id. Must exists.
2881 * @throws \dml_exception
83e3a4fe 2882 * @throws \moodle_exception If trying to remove a member(s) from a non-group conversation
623048af
AA
2883 */
2884 public static function remove_members_from_conversation(array $userids, int $convid) {
2885 global $DB;
2886
2887 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2888
83e3a4fe
MN
2889 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2890 throw new \moodle_exception('You can not remove members from a non-group conversation.');
2891 }
2892
623048af
AA
2893 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2894 $params['convid'] = $convid;
2895
623048af
AA
2896 $DB->delete_records_select('message_conversation_members',
2897 "conversationid = :convid AND userid $useridcondition", $params);
623048af
AA
2898 }
2899
2900 /**
2901 * Count conversation members.
2902 *
2903 * @param int $convid The conversation id.
2904 * @return int Number of conversation members.
2905 * @throws \dml_exception
2906 */
2907 public static function count_conversation_members(int $convid) : int {
2908 global $DB;
08cb8a34 2909
623048af 2910 return $DB->count_records('message_conversation_members', ['conversationid' => $convid]);
08cb8a34 2911 }
55fda006 2912
f0e137c5
MN
2913 /**
2914 * Checks whether or not a conversation area is enabled.
2915 *
2916 * @param string $component Defines the Moodle component which the area was added to.
2917 * @param string $itemtype Defines the type of the component.
2918 * @param int $itemid The id of the component.
2919 * @param int $contextid The id of the context.
2920 * @return bool Returns if a conversation area exists and is enabled, false otherwise
2921 */
2922 public static function is_conversation_area_enabled(string $component, string $itemtype, int $itemid, int $contextid) : bool {
2923 global $DB;
2924
76540bec 2925 return $DB->record_exists('message_conversations',
f0e137c5
MN
2926 [
2927 'itemid' => $itemid,
2928 'contextid' => $contextid,
2929 'component' => $component,
2930 'itemtype' => $itemtype,
76540bec 2931 'enabled' => self::MESSAGE_CONVERSATION_ENABLED
f0e137c5
MN
2932 ]
2933 );
2934 }
2935
e7f46714 2936 /**
76540bec 2937 * Get conversation by area.
e7f46714 2938 *
2939 * @param string $component Defines the Moodle component which the area was added to.
2940 * @param string $itemtype Defines the type of the component.
76540bec
MN
2941 * @param int $itemid The id of the component.
2942 * @param int $contextid The id of the context.
2943 * @return \stdClass
e7f46714 2944 */
76540bec 2945 public static function get_conversation_by_area(string $component, string $itemtype, int $itemid, int $contextid) {
e7f46714 2946 global $DB;
2947
76540bec 2948 return $DB->get_record('message_conversations',
f0e137c5
MN
2949 [
2950 'itemid' => $itemid,
2951 'contextid' => $contextid,
2952 'component' => $component,
2953 'itemtype' => $itemtype
2954 ]
2955 );
e7f46714 2956 }
2957
2958 /**
76540bec 2959 * Enable a conversation.
e7f46714 2960 *
76540bec 2961 * @param int $conversationid The id of the conversation.
e7f46714 2962 * @return void
2963 */
76540bec 2964 public static function enable_conversation(int $conversationid) {
e7f46714 2965 global $DB;
2966
76540bec
MN
2967 $conversation = new \stdClass();
2968 $conversation->id = $conversationid;
2969 $conversation->enabled = self::MESSAGE_CONVERSATION_ENABLED;
2970 $conversation->timemodified = time();
2971 $DB->update_record('message_conversations', $conversation);
e7f46714 2972 }
2973
2974 /**
76540bec 2975 * Disable a conversation.
e7f46714 2976 *
76540bec 2977 * @param int $conversationid The id of the conversation.
e7f46714 2978 * @return void
2979 */
76540bec 2980 public static function disable_conversation(int $conversationid) {
e7f46714 2981 global $DB;
2982
76540bec
MN
2983 $conversation = new \stdClass();
2984 $conversation->id = $conversationid;
2985 $conversation->enabled = self::MESSAGE_CONVERSATION_DISABLED;
2986 $conversation->timemodified = time();
2987 $DB->update_record('message_conversations', $conversation);
e7f46714 2988 }
2989
2990 /**
2991 * Update the name of a conversation.
2992 *
76540bec 2993 * @param int $conversationid The id of a conversation.
e7f46714 2994 * @param string $name The main name of the area
2995 * @return void
2996 */
2997 public static function update_conversation_name(int $conversationid, string $name) {
2998 global $DB;
2999
3000 if ($conversation = $DB->get_record('message_conversations', array('id' => $conversationid))) {
3001 if ($name <> $conversation->name) {
3002 $conversation->name = $name;
f0e137c5 3003 $conversation->timemodified = time();
e7f46714 3004 $DB->update_record('message_conversations', $conversation);
3005 }
3006 }
3007 }
6ecd6e5b
MN
3008
3009 /**
3010 * Returns a list of conversation members.
3011 *
3012 * @param int $userid The user we are returning the conversation members for, used by helper::get_member_info.
3013 * @param int $conversationid The id of the conversation
3014 * @param bool $includecontactrequests Do we want to include contact requests with this data?
663ccd58 3015 * @param bool $includeprivacyinfo Do we want to include privacy requests with this data?
6ecd6e5b
MN
3016 * @param int $limitfrom
3017 * @param int $limitnum
3018 * @return array
3019 */
3020 public static function get_conversation_members(int $userid, int $conversationid, bool $includecontactrequests = false,
663ccd58
RW
3021 bool $includeprivacyinfo = false, int $limitfrom = 0,
3022 int $limitnum = 0) : array {
6ecd6e5b
MN
3023 global $DB;
3024
3025 if ($members = $DB->get_records('message_conversation_members', ['conversationid' => $conversationid],
3026 'timecreated ASC, id ASC', 'userid', $limitfrom, $limitnum)) {
3027 $userids = array_keys($members);
663ccd58 3028 $members = helper::get_member_info($userid, $userids, $includecontactrequests, $includeprivacyinfo);
6ecd6e5b
MN
3029
3030 return $members;
3031 }
3032
3033 return [];
3034 }
33022ee1
JD
3035
3036 /**
3037 * Get the unread counts for all conversations for the user, sorted by type, and including favourites.
3038 *
3039 * @param int $userid the id of the user whose conversations we'll check.
3040 * @return array the unread counts for each conversation, indexed by type.
3041 */
3042 public static function get_unread_conversation_counts(int $userid) : array {
3043 global $DB;
3044
3045 // Get all conversations the user is in, and check unread.
3046 $unreadcountssql = 'SELECT conv.id, conv.type, indcounts.unreadcount
3047 FROM {message_conversations} conv
3048 INNER JOIN (
3049 SELECT m.conversationid, count(m.id) as unreadcount
3050 FROM {messages} m
3051 INNER JOIN {message_conversations} mc
3052 ON mc.id = m.conversationid
3053 INNER JOIN {message_conversation_members} mcm
3054 ON m.conversationid = mcm.conversationid
3055 LEFT JOIN {message_user_actions} mua
3056 ON (mua.messageid = m.id AND mua.userid = ? AND
3057 (mua.action = ? OR mua.action = ?))
3058 WHERE mcm.userid = ?
3059 AND m.useridfrom != ?
3060 AND mua.id is NULL
3061 GROUP BY m.conversationid
3062 ) indcounts
3063 ON indcounts.conversationid = conv.id
3064 WHERE conv.enabled = 1';
3065
3066 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
3067 $userid, $userid]);
3068
3069 // Get favourites, so we can track these separately.
3070 $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
3071 $favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
3072 $favouriteconvids = array_flip(array_column($favouriteconversations, 'itemid'));
3073
3074 // Assemble the return array.
3075 $counts = ['favourites' => 0, 'types' => [
3076 self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL => 0,
3077 self::MESSAGE_CONVERSATION_TYPE_GROUP => 0
3078 ]];
3079 foreach ($unreadcounts as $convid => $info) {
33022ee1
JD
3080 if (isset($favouriteconvids[$convid])) {
3081 $counts['favourites']++;
a5411535 3082 continue;
33022ee1 3083 }
a5411535 3084 $counts['types'][$info->type]++;
33022ee1
JD
3085 }
3086
3087 return $counts;
3088 }
879e2bef 3089}