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