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