MDL-64057 core_favourites: add get_join_sql_by_type() to service layer
[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) {
aa748351
JD
733 // Do not include any individual conversation which:
734 // a) Contains a deleted member or
735 // b) Does not contain a recent message for the user (this happens if the user has deleted all messages).
736 // Group conversations with deleted users or no messages are always returned.
737 if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL
738 && (isset($deletedmembers[$conversation->id]) || empty($conversation->messageid))) {
883ce421
MN
739 continue;
740 }
741
eb5865da
JD
742 $conv = new \stdClass();
743 $conv->id = $conversation->id;
744 $conv->name = $conversation->conversationname;
003cdcce
JD
745 $conv->subname = $convextrafields[$conv->id]['subname'] ?? null;
746 $conv->imageurl = $convextrafields[$conv->id]['imageurl'] ?? null;
eb5865da
JD
747 $conv->type = $conversation->conversationtype;
748 $conv->membercount = $membercounts[$conv->id]->membercount;
749 $conv->isfavourite = in_array($conv->id, $favouriteconversationids);
750 $conv->isread = isset($unreadcounts[$conv->id]) ? false : true;
751 $conv->unreadcount = isset($unreadcounts[$conv->id]) ? $unreadcounts[$conv->id]->unreadcount : null;
752 $conv->members = $members[$conv->id];
753
754 // Add the most recent message information.
755 $conv->messages = [];
756 if ($conversation->smallmessage) {
757 $msg = new \stdClass();
758 $msg->id = $conversation->messageid;
74fc14e5 759 $msg->text = message_format_message_text($conversation);
eb5865da
JD
760 $msg->useridfrom = $conversation->useridfrom;
761 $msg->timecreated = $conversation->timecreated;
762 $conv->messages[] = $msg;
349f4261
RW
763 }
764
eb5865da 765 $arrconversations[] = $conv;
879e2bef 766 }
de55cb1b 767 return $arrconversations;
879e2bef
MN
768 }
769
548cac7d
AA
770 /**
771 * Returns all conversations between two users
772 *
773 * @param int $userid1 One of the user's id
774 * @param int $userid2 The other user's id
775 * @param int $limitfrom
776 * @param int $limitnum
777 * @return array
778 * @throws \dml_exception
779 */
780 public static function get_conversations_between_users(int $userid1, int $userid2,
781 int $limitfrom = 0, int $limitnum = 20) : array {
782
783 global $DB;
784
785 if ($userid1 == $userid2) {
786 return array();
787 }
788
789 // Get all conversation where both user1 and user2 are members.
790 // TODO: Add subname value. Waiting for definite table structure.
791 $sql = "SELECT mc.id, mc.type, mc.name, mc.timecreated
792 FROM {message_conversations} mc
793 INNER JOIN {message_conversation_members} mcm1
794 ON mc.id = mcm1.conversationid
795 INNER JOIN {message_conversation_members} mcm2
796 ON mc.id = mcm2.conversationid
797 WHERE mcm1.userid = :userid1
798 AND mcm2.userid = :userid2
799 AND mc.enabled != 0
800 ORDER BY mc.timecreated DESC";
801
802 return $DB->get_records_sql($sql, array('userid1' => $userid1, 'userid2' => $userid2), $limitfrom, $limitnum);
803 }
804
4e313026
RW
805 /**
806 * Return a conversation.
807 *
808 * @param int $userid The user id to get the conversation for
809 * @param int $conversationid The id of the conversation to fetch
810 * @param bool $includecontactrequests Should contact requests be included between members
811 * @param bool $includeprivacyinfo Should privacy info be included between members
812 * @param int $memberlimit Limit number of members to load
813 * @param int $memberoffset Offset members by this amount
814 * @param int $messagelimit Limit number of messages to load
815 * @param int $messageoffset Offset the messages
816 * @param bool $newestmessagesfirst Order messages by newest first
817 * @return \stdClass
818 */
819 public static function get_conversation(
820 int $userid,
821 int $conversationid,
822 bool $includecontactrequests = false,
823 bool $includeprivacyinfo = false,
824 int $memberlimit = 0,
825 int $memberoffset = 0,
826 int $messagelimit = 0,
827 int $messageoffset = 0,
828 bool $newestmessagesfirst = true
829 ) {
830 global $USER, $DB;
831
832 $systemcontext = \context_system::instance();
833 $canreadallmessages = has_capability('moodle/site:readallmessages', $systemcontext);
834 if (($USER->id != $userid) && !$canreadallmessages) {
835 throw new \moodle_exception('You do not have permission to perform this action.');
836 }
837
838 $conversation = $DB->get_record('message_conversations', ['id' => $conversationid]);
839 if (!$conversation) {
840 return null;
841 }
842
843 $isconversationmember = $DB->record_exists(
844 'message_conversation_members',
845 [
846 'conversationid' => $conversationid,
847 'userid' => $userid
848 ]
849 );
850
851 if (!$isconversationmember && !$canreadallmessages) {
852 throw new \moodle_exception('You do not have permission to view this conversation.');
853 }
854
855 $members = self::get_conversation_members(
856 $userid,
857 $conversationid,
858 $includecontactrequests,
663ccd58 859 $includeprivacyinfo,
4e313026
RW
860 $memberoffset,
861 $memberlimit
862 );
863 // Strip out the requesting user to match what get_conversations does.
864 $members = array_filter($members, function($member) use ($userid) {
865 return $member->id != $userid;
866 });
867
868 $messages = self::get_conversation_messages(
869 $userid,
870 $conversationid,
871 $messageoffset,
872 $messagelimit,
873 $newestmessagesfirst ? 'timecreated DESC' : 'timecreated ASC'
874 );
875
876 $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
877 $isfavourite = $service->favourite_exists('core_message', 'message_conversations', $conversationid, $systemcontext);
878
879 $convextrafields = self::get_linked_conversation_extra_fields([$conversation]);
880 $subname = isset($convextrafields[$conversationid]) ? $convextrafields[$conversationid]['subname'] : null;
881 $imageurl = isset($convextrafields[$conversationid]) ? $convextrafields[$conversationid]['imageurl'] : null;
882
883 $unreadcountssql = 'SELECT count(m.id)
884 FROM {messages} m
885 INNER JOIN {message_conversations} mc
886 ON mc.id = m.conversationid
887 LEFT JOIN {message_user_actions} mua
888 ON (mua.messageid = m.id AND mua.userid = ? AND
889 (mua.action = ? OR mua.action = ?))
890 WHERE m.conversationid = ?
891 AND m.useridfrom != ?
892 AND mua.id is NULL';
893 $unreadcount = $DB->count_records_sql(
894 $unreadcountssql,
895 [
896 $userid,
897 self::MESSAGE_ACTION_READ,
898 self::MESSAGE_ACTION_DELETED,
899 $conversationid,
900 $userid
901 ]
902 );
903
904 $membercount = $DB->count_records('message_conversation_members', ['conversationid' => $conversationid]);
905
906 return (object) [
907 'id' => $conversation->id,
908 'name' => $conversation->name,
909 'subname' => $subname,
910 'imageurl' => $imageurl,
911 'type' => $conversation->type,
912 'membercount' => $membercount,
913 'isfavourite' => $isfavourite,
914 'isread' => empty($unreadcount),
915 'unreadcount' => $unreadcount,
916 'members' => $members,
917 'messages' => $messages['messages']
918 ];
919 }
920
b8ff2c44
JD
921 /**
922 * Mark a conversation as a favourite for the given user.
923 *
924 * @param int $conversationid the id of the conversation to mark as a favourite.
925 * @param int $userid the id of the user to whom the favourite belongs.
926 * @return favourite the favourite object.
927 * @throws \moodle_exception if the user or conversation don't exist.
928 */
929 public static function set_favourite_conversation(int $conversationid, int $userid) : favourite {
6b036d04
SA
930 global $DB;
931
b8ff2c44
JD
932 if (!self::is_user_in_conversation($userid, $conversationid)) {
933 throw new \moodle_exception("Conversation doesn't exist or user is not a member");
934 }
6b036d04
SA
935 // Get the context for this conversation.
936 $conversation = $DB->get_record('message_conversations', ['id' => $conversationid]);
937 $userctx = \context_user::instance($userid);
938 if (empty($conversation->contextid)) {
939 // When the conversation hasn't any contextid value defined, the favourite will be added to the user context.
940 $conversationctx = $userctx;
9e189a91 941 } else {
6b036d04
SA
942 // If the contextid is defined, the favourite will be added there.
943 $conversationctx = \context::instance_by_id($conversation->contextid);
9e189a91 944 }
6b036d04
SA
945
946 $ufservice = \core_favourites\service_factory::get_service_for_user_context($userctx);
2f7076eb
AN
947
948 if ($favourite = $ufservice->get_favourite('core_message', 'message_conversations', $conversationid, $conversationctx)) {
949 return $favourite;
950 } else {
951 return $ufservice->create_favourite('core_message', 'message_conversations', $conversationid, $conversationctx);
952 }
b8ff2c44
JD
953 }
954
955 /**
956 * Unset a conversation as a favourite for the given user.
957 *
958 * @param int $conversationid the id of the conversation to unset as a favourite.
959 * @param int $userid the id to whom the favourite belongs.
960 * @throws \moodle_exception if the favourite does not exist for the user.
961 */
962 public static function unset_favourite_conversation(int $conversationid, int $userid) {
6b036d04
SA
963 global $DB;
964
965 // Get the context for this conversation.
43f68992 966 $conversation = $DB->get_record('message_conversations', ['id' => $conversationid]);
6b036d04
SA
967 $userctx = \context_user::instance($userid);
968 if (empty($conversation->contextid)) {
969 // When the conversation hasn't any contextid value defined, the favourite will be added to the user context.
970 $conversationctx = $userctx;
971 } else {
972 // If the contextid is defined, the favourite will be added there.
973 $conversationctx = \context::instance_by_id($conversation->contextid);
974 }
975
976 $ufservice = \core_favourites\service_factory::get_service_for_user_context($userctx);
977 $ufservice->delete_favourite('core_message', 'message_conversations', $conversationid, $conversationctx);
b8ff2c44
JD
978 }
979
879e2bef
MN
980 /**
981 * Returns the contacts to display in the contacts area.
982 *
4461288d
MN
983 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
984 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
985 * Followup: MDL-63915
986 *
879e2bef
MN
987 * @param int $userid The user id
988 * @param int $limitfrom
989 * @param int $limitnum
de55cb1b 990 * @return array
879e2bef
MN
991 */
992 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
993 global $DB;
994
f219eac7
MN
995 $contactids = [];
996 $sql = "SELECT mc.*
879e2bef 997 FROM {message_contacts} mc
f219eac7
MN
998 WHERE mc.userid = ? OR mc.contactid = ?
999 ORDER BY timecreated DESC";
1000 if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
879e2bef 1001 foreach ($contacts as $contact) {
f219eac7
MN
1002 if ($userid == $contact->userid) {
1003 $contactids[] = $contact->contactid;
1004 } else {
1005 $contactids[] = $contact->userid;
1006 }
1007 }
1008 }
1009
1010 if (!empty($contactids)) {
1011 list($insql, $inparams) = $DB->get_in_or_equal($contactids);
1012
1013 $sql = "SELECT u.*, mub.id as isblocked
1014 FROM {user} u
1015 LEFT JOIN {message_users_blocked} mub
1016 ON u.id = mub.blockeduserid
1017 WHERE u.id $insql";
1018 if ($contacts = $DB->get_records_sql($sql, $inparams)) {
1019 $arrcontacts = [];
1020 foreach ($contacts as $contact) {
1021 $contact->blocked = $contact->isblocked ? 1 : 0;
1022 $arrcontacts[] = helper::create_contact($contact);
1023 }
1024
1025 return $arrcontacts;
879e2bef
MN
1026 }
1027 }
1028
f219eac7 1029 return [];
879e2bef
MN
1030 }
1031
ecb4755c
RW
1032 /**
1033 * Returns the contacts count.
1034 *
1035 * @param int $userid The user id
1036 * @return array
1037 */
1038 public static function count_contacts(int $userid) : int {
1039 global $DB;
1040
1041 $sql = "SELECT COUNT(id)
1042 FROM {message_contacts}
1043 WHERE userid = ? OR contactid = ?";
1044 return $DB->count_records_sql($sql, [$userid, $userid]);
1045 }
1046
883ce421
MN
1047 /**
1048 * Returns the an array of the users the given user is in a conversation
1049 * with who are a contact and the number of unread messages.
1050 *
1051 * @param int $userid The user id
1052 * @param int $limitfrom
1053 * @param int $limitnum
1054 * @return array
1055 */
1056 public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
1057 global $DB;
1058
1059 $userfields = \user_picture::fields('u', array('lastaccess'));
1060 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
1061 FROM {message_contacts} mc
1062 INNER JOIN {user} u
f219eac7 1063 ON (u.id = mc.contactid OR u.id = mc.userid)
883ce421 1064 LEFT JOIN {messages} m
f219eac7 1065 ON ((m.useridfrom = mc.contactid OR m.useridfrom = mc.userid) AND m.useridfrom != ?)
883ce421
MN
1066 LEFT JOIN {message_conversation_members} mcm
1067 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
1068 LEFT JOIN {message_user_actions} mua
1069 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
f219eac7
MN
1070 LEFT JOIN {message_users_blocked} mub
1071 ON (mub.userid = ? AND mub.blockeduserid = u.id)
883ce421 1072 WHERE mua.id is NULL
f219eac7
MN
1073 AND mub.id is NULL
1074 AND (mc.userid = ? OR mc.contactid = ?)
1075 AND u.id != ?
883ce421
MN
1076 AND u.deleted = 0
1077 GROUP BY $userfields";
1078
f219eac7
MN
1079 return $DB->get_records_sql($unreadcountssql, [$userid, $userid, $userid, self::MESSAGE_ACTION_READ,
1080 $userid, $userid, $userid, $userid], $limitfrom, $limitnum);
883ce421
MN
1081 }
1082
1083 /**
1084 * Returns the an array of the users the given user is in a conversation
1085 * with who are not a contact and the number of unread messages.
1086 *
1087 * @param int $userid The user id
1088 * @param int $limitfrom
1089 * @param int $limitnum
1090 * @return array
1091 */
1092 public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
1093 global $DB;
1094
1095 $userfields = \user_picture::fields('u', array('lastaccess'));
1096 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
1097 FROM {user} u
1098 INNER JOIN {messages} m
1099 ON m.useridfrom = u.id
1100 INNER JOIN {message_conversation_members} mcm
1101 ON mcm.conversationid = m.conversationid
1102 LEFT JOIN {message_user_actions} mua
1103 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1104 LEFT JOIN {message_contacts} mc
1105 ON (mc.userid = ? AND mc.contactid = u.id)
f219eac7
MN
1106 LEFT JOIN {message_users_blocked} mub
1107 ON (mub.userid = ? AND mub.blockeduserid = u.id)
883ce421
MN
1108 WHERE mcm.userid = ?
1109 AND mcm.userid != m.useridfrom
1110 AND mua.id is NULL
f219eac7 1111 AND mub.id is NULL
883ce421
MN
1112 AND mc.id is NULL
1113 AND u.deleted = 0
1114 GROUP BY $userfields";
1115
f219eac7 1116 return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
883ce421
MN
1117 $limitfrom, $limitnum);
1118 }
1119
879e2bef
MN
1120 /**
1121 * Returns the messages to display in the message area.
1122 *
4461288d
MN
1123 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1124 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1125 * Followup: MDL-63915
1126 *
879e2bef
MN
1127 * @param int $userid the current user
1128 * @param int $otheruserid the other user
1129 * @param int $limitfrom
1130 * @param int $limitnum
8ec78c48 1131 * @param string $sort
ffd7798c
MN
1132 * @param int $timefrom the time from the message being sent
1133 * @param int $timeto the time up until the message being sent
de55cb1b 1134 * @return array
879e2bef 1135 */
fb1469d8 1136 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
d1e8e69d 1137 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
fb1469d8 1138
ffd7798c 1139 if (!empty($timefrom)) {
fb04293b
SA
1140 // Get the conversation between userid and otheruserid.
1141 $userids = [$userid, $otheruserid];
1142 if (!$conversationid = self::get_conversation_between_users($userids)) {
1143 // This method was always used for individual conversations.
1144 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
1145 $conversationid = $conversation->id;
1146 }
1147
fb1469d8 1148 // Check the cache to see if we even need to do a DB query.
4699b8bc
AN
1149 $cache = \cache::make('core', 'message_time_last_message_between_users');
1150 $key = helper::get_last_message_time_created_cache_key($conversationid);
1151 $lastcreated = $cache->get($key);
fb1469d8
RW
1152
1153 // The last known message time is earlier than the one being requested so we can
1154 // just return an empty result set rather than having to query the DB.
ffd7798c 1155 if ($lastcreated && $lastcreated < $timefrom) {
fb1469d8
RW
1156 return [];
1157 }
1158 }
1159
879e2bef 1160 $arrmessages = array();
fb1469d8 1161 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
ffd7798c 1162 $sort, $timefrom, $timeto)) {
de55cb1b 1163 $arrmessages = helper::create_messages($userid, $messages);
879e2bef
MN
1164 }
1165
de55cb1b 1166 return $arrmessages;
879e2bef 1167 }
c060cd49 1168
fb04293b
SA
1169 /**
1170 * Returns the messages for the defined conversation.
1171 *
1172 * @param int $userid The current user.
1173 * @param int $convid The conversation where the messages belong. Could be an object or just the id.
1174 * @param int $limitfrom Return a subset of records, starting at this point (optional).
1175 * @param int $limitnum Return a subset comprising this many records in total (optional, required if $limitfrom is set).
1176 * @param string $sort The column name to order by including optionally direction.
1177 * @param int $timefrom The time from the message being sent.
1178 * @param int $timeto The time up until the message being sent.
1179 * @return array of messages
1180 */
1181 public static function get_conversation_messages(int $userid, int $convid, int $limitfrom = 0, int $limitnum = 0,
1182 string $sort = 'timecreated ASC', int $timefrom = 0, int $timeto = 0) : array {
1183
1184 if (!empty($timefrom)) {
1185 // Check the cache to see if we even need to do a DB query.
74138e92 1186 $cache = \cache::make('core', 'message_time_last_message_between_users');
4699b8bc
AN
1187 $key = helper::get_last_message_time_created_cache_key($convid);
1188 $lastcreated = $cache->get($key);
fb04293b
SA
1189
1190 // The last known message time is earlier than the one being requested so we can
1191 // just return an empty result set rather than having to query the DB.
1192 if ($lastcreated && $lastcreated < $timefrom) {
1193 return [];
1194 }
1195 }
1196
32b4212e
RW
1197 $messages = helper::get_conversation_messages($userid, $convid, 0, $limitfrom, $limitnum, $sort, $timefrom, $timeto);
1198 return helper::format_conversation_messages($userid, $convid, $messages);
fb04293b
SA
1199 }
1200
c060cd49
MN
1201 /**
1202 * Returns the most recent message between two users.
1203 *
4461288d
MN
1204 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1205 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1206 * Followup: MDL-63915
1207 *
c060cd49
MN
1208 * @param int $userid the current user
1209 * @param int $otheruserid the other user
de55cb1b 1210 * @return \stdClass|null
c060cd49
MN
1211 */
1212 public static function get_most_recent_message($userid, $otheruserid) {
1213 // We want two messages here so we get an accurate 'blocktime' value.
de55cb1b 1214 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
1215 // Swap the order so we now have them in historical order.
1216 $messages = array_reverse($messages);
de55cb1b 1217 $arrmessages = helper::create_messages($userid, $messages);
c060cd49
MN
1218 return array_pop($arrmessages);
1219 }
1220
1221 return null;
1222 }
c6e97f54 1223
fb04293b
SA
1224 /**
1225 * Returns the most recent message in a conversation.
1226 *
1227 * @param int $convid The conversation identifier.
1228 * @param int $currentuserid The current user identifier.
1229 * @return \stdClass|null The most recent message.
1230 */
1231 public static function get_most_recent_conversation_message(int $convid, int $currentuserid = 0) {
1232 global $USER;
1233
1234 if (empty($currentuserid)) {
1235 $currentuserid = $USER->id;
1236 }
1237
1238 if ($messages = helper::get_conversation_messages($currentuserid, $convid, 0, 0, 1, 'timecreated DESC')) {
1239 $convmessages = helper::format_conversation_messages($currentuserid, $convid, $messages);
1240 return array_pop($convmessages['messages']);
1241 }
1242
1243 return null;
1244 }
1245
c6e97f54
MN
1246 /**
1247 * Returns the profile information for a contact for a user.
1248 *
4461288d
MN
1249 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1250 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1251 * Followup: MDL-63915
1252 *
c6e97f54
MN
1253 * @param int $userid The user id
1254 * @param int $otheruserid The id of the user whose profile we want to view.
de55cb1b 1255 * @return \stdClass
c6e97f54
MN
1256 */
1257 public static function get_profile($userid, $otheruserid) {
f219eac7 1258 global $CFG, $PAGE;
c6e97f54
MN
1259
1260 require_once($CFG->dirroot . '/user/lib.php');
1261
f4c39cb9
MN
1262 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
1263
1264 // Create the data we are going to pass to the renderable.
1265 $data = new \stdClass();
1266 $data->userid = $otheruserid;
1267 $data->fullname = fullname($user);
1268 $data->city = '';
1269 $data->country = '';
1270 $data->email = '';
cb805753 1271 $data->isonline = null;
f4c39cb9
MN
1272 // Get the user picture data - messaging has always shown these to the user.
1273 $userpicture = new \user_picture($user);
1274 $userpicture->size = 1; // Size f1.
1275 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
1276 $userpicture->size = 0; // Size f2.
1277 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
1278
1279 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
1280 if ($userfields) {
1281 if (isset($userfields['city'])) {
1282 $data->city = $userfields['city'];
1283 }
1284 if (isset($userfields['country'])) {
1285 $data->country = $userfields['country'];
bf58081d 1286 }
f4c39cb9
MN
1287 if (isset($userfields['email'])) {
1288 $data->email = $userfields['email'];
c6e97f54 1289 }
f4c39cb9
MN
1290 if (isset($userfields['lastaccess'])) {
1291 $data->isonline = helper::is_online($userfields['lastaccess']);
1292 }
1293 }
c6e97f54 1294
f219eac7
MN
1295 $data->isblocked = self::is_blocked($userid, $otheruserid);
1296 $data->iscontact = self::is_contact($userid, $otheruserid);
f4c39cb9
MN
1297
1298 return $data;
c6e97f54 1299 }
dec0cd99
MN
1300
1301 /**
1302 * Checks if a user can delete messages they have either received or sent.
1303 *
1304 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1305 * but will still seem as if it was by the user)
15663b0b 1306 * @param int $conversationid The id of the conversation
1f64514d 1307 * @return bool Returns true if a user can delete the conversation, false otherwise.
dec0cd99 1308 */
15663b0b 1309 public static function can_delete_conversation(int $userid, int $conversationid = null) : bool {
dec0cd99
MN
1310 global $USER;
1311
15663b0b
MN
1312 if (is_null($conversationid)) {
1313 debugging('\core_message\api::can_delete_conversation() now expects a \'conversationid\' to be passed.',
1314 DEBUG_DEVELOPER);
1315 return false;
1316 }
1317
dec0cd99
MN
1318 $systemcontext = \context_system::instance();
1319
15663b0b
MN
1320 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1321 return true;
1322 }
1323
1324 if (!self::is_user_in_conversation($userid, $conversationid)) {
1325 return false;
1326 }
1327
1328 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1329 $USER->id == $userid) {
dec0cd99
MN
1330 return true;
1331 }
1332
1333 return false;
1334 }
1335
1336 /**
1337 * Deletes a conversation.
1338 *
1339 * This function does not verify any permissions.
1340 *
263ad984 1341 * @deprecated since 3.6
dec0cd99
MN
1342 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1343 * but will still seem as if it was by the user)
1344 * @param int $otheruserid The id of the other user in the conversation
1345 * @return bool
1346 */
1347 public static function delete_conversation($userid, $otheruserid) {
263ad984
MN
1348 debugging('\core_message\api::delete_conversation() is deprecated, please use ' .
1349 '\core_message\api::delete_conversation_by_id() instead.', DEBUG_DEVELOPER);
dec0cd99 1350
b2cd17e6 1351 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
dec0cd99 1352
883ce421
MN
1353 // If there is no conversation, there is nothing to do.
1354 if (!$conversationid) {
1355 return true;
1356 }
1357
263ad984
MN
1358 self::delete_conversation_by_id($userid, $conversationid);
1359
1360 return true;
1361 }
1362
1363 /**
1364 * Deletes a conversation for a specified user.
1365 *
1366 * This function does not verify any permissions.
1367 *
1368 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1369 * but will still seem as if it was by the user)
1370 * @param int $conversationid The id of the other user in the conversation
1371 */
1372 public static function delete_conversation_by_id(int $userid, int $conversationid) {
1373 global $DB, $USER;
1374
883ce421
MN
1375 // Get all messages belonging to this conversation that have not already been deleted by this user.
1376 $sql = "SELECT m.*
1377 FROM {messages} m
1378 INNER JOIN {message_conversations} mc
1379 ON m.conversationid = mc.id
1380 LEFT JOIN {message_user_actions} mua
1381 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1382 WHERE mua.id is NULL
1383 AND mc.id = ?
1384 ORDER BY m.timecreated ASC";
1385 $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
1386
1387 // Ok, mark these as deleted.
1388 foreach ($messages as $message) {
1389 $mua = new \stdClass();
1390 $mua->userid = $userid;
1391 $mua->messageid = $message->id;
1392 $mua->action = self::MESSAGE_ACTION_DELETED;
1393 $mua->timecreated = time();
1394 $mua->id = $DB->insert_record('message_user_actions', $mua);
1395
14de10c4
MN
1396 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1397 $message->id, $mua->id)->trigger();
dec0cd99 1398 }
dec0cd99 1399 }
79f6c36c
MN
1400
1401 /**
1402 * Returns the count of unread conversations (collection of messages from a single user) for
1403 * the given user.
1404 *
1405 * @param \stdClass $user the user who's conversations should be counted
1406 * @return int the count of the user's unread conversations
1407 */
1408 public static function count_unread_conversations($user = null) {
1409 global $USER, $DB;
1410
1411 if (empty($user)) {
1412 $user = $USER;
1413 }
1414
883ce421
MN
1415 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
1416 FROM {messages} m
1417 INNER JOIN {message_conversations} mc
1418 ON m.conversationid = mc.id
1419 INNER JOIN {message_conversation_members} mcm
1420 ON mc.id = mcm.conversationid
1421 LEFT JOIN {message_user_actions} mua
1422 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1423 WHERE mcm.userid = ?
1424 AND mcm.userid != m.useridfrom
1425 AND mua.id is NULL";
1426
1427 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
79f6c36c
MN
1428 }
1429
abf7a261
MN
1430 /**
1431 * Checks if a user can mark all messages as read.
1432 *
1433 * @param int $userid The user id of who we want to mark the messages for
1434 * @param int $conversationid The id of the conversation
1435 * @return bool true if user is permitted, false otherwise
1436 * @since 3.6
1437 */
1438 public static function can_mark_all_messages_as_read(int $userid, int $conversationid) : bool {
1439 global $USER;
1440
1441 $systemcontext = \context_system::instance();
1442
1443 if (has_capability('moodle/site:readallmessages', $systemcontext)) {
1444 return true;
1445 }
1446
1447 if (!self::is_user_in_conversation($userid, $conversationid)) {
1448 return false;
1449 }
1450
1451 if ($USER->id == $userid) {
1452 return true;
1453 }
1454
1455 return false;
1456 }
1457
6399c7ef
RW
1458 /**
1459 * Returns the count of conversations (collection of messages from a single user) for
1460 * the given user.
1461 *
1462 * @param \stdClass $user The user who's conversations should be counted
1463 * @param int $type The conversation type
1464 * @param bool $excludefavourites Exclude favourite conversations
1465 * @return int the count of the user's unread conversations
1466 */
1467 public static function count_conversations($user, int $type = null, bool $excludefavourites = false) {
1468 global $DB;
1469
1470 $params = [];
1471 $favouritessql = '';
1472
1473 if ($excludefavourites) {
1474 $favouritessql = "AND m.conversationid NOT IN (
1475 SELECT itemid
1476 FROM {favourite}
1477 WHERE component = 'core_message'
1478 AND itemtype = 'message_conversations'
1479 AND userid = ?
1480 )";
1481 $params[] = $user->id;
1482 }
1483
1484 switch($type) {
1485 case null:
1486 $params = array_merge([$user->id, self::MESSAGE_ACTION_DELETED, $user->id], $params);
1487 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
1488 FROM {messages} m
1489 LEFT JOIN {message_conversations} c
1490 ON m.conversationid = c.id
1491 LEFT JOIN {message_user_actions} ma
1492 ON ma.messageid = m.id
1493 LEFT JOIN {message_conversation_members} mcm
1494 ON m.conversationid = mcm.conversationid
1495 WHERE mcm.userid = ?
1496 AND (
1497 c.type != " . self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL . "
1498 OR
1499 (
1500 (ma.action IS NULL OR ma.action != ? OR ma.userid != ?)
1501 AND c.type = " . self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL . "
1502 )
1503 )
1504 ${favouritessql}";
1505 break;
1506 case self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL:
1507 $params = array_merge([self::MESSAGE_ACTION_DELETED, $user->id, $user->id], $params);
1508 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
1509 FROM {messages} m
1510 LEFT JOIN {message_conversations} c
1511 ON m.conversationid = c.id
1512 LEFT JOIN {message_user_actions} ma
1513 ON ma.messageid = m.id
1514 LEFT JOIN {message_conversation_members} mcm
1515 ON m.conversationid = mcm.conversationid
1516 WHERE (ma.action IS NULL OR ma.action != ? OR ma.userid != ?)
1517 AND mcm.userid = ?
1518 AND c.type = " . self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL . "
1519 ${favouritessql}";
1520 break;
1521 default:
1522 $params = array_merge([$user->id, $type], $params);
1523 $sql = "SELECT COUNT(m.conversationid)
1524 FROM {message_conversation_members} m
1525 LEFT JOIN {message_conversations} c
1526 ON m.conversationid = c.id
1527 WHERE m.userid = ?
1528 AND c.type = ?
1529 ${favouritessql}";
1530
1531 }
1532
1533 return $DB->count_records_sql($sql, $params);
1534 }
1535
79f6c36c 1536 /**
74ad60bf 1537 * Marks all messages being sent to a user in a particular conversation.
79f6c36c 1538 *
74ad60bf 1539 * If $conversationdid is null then it marks all messages as read sent to $userid.
79f6c36c 1540 *
74ad60bf
MN
1541 * @param int $userid
1542 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
79f6c36c 1543 */
74ad60bf 1544 public static function mark_all_messages_as_read($userid, $conversationid = null) {
79f6c36c
MN
1545 global $DB;
1546
883ce421
MN
1547 $messagesql = "SELECT m.*
1548 FROM {messages} m
1549 INNER JOIN {message_conversations} mc
1550 ON mc.id = m.conversationid
1551 INNER JOIN {message_conversation_members} mcm
1552 ON mcm.conversationid = mc.id
5aac33c7
MN
1553 LEFT JOIN {message_user_actions} mua
1554 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1555 WHERE mua.id is NULL
1556 AND mcm.userid = ?
74ad60bf 1557 AND m.useridfrom != ?";
5aac33c7
MN
1558 $messageparams = [];
1559 $messageparams[] = $userid;
1560 $messageparams[] = self::MESSAGE_ACTION_READ;
74ad60bf
MN
1561 $messageparams[] = $userid;
1562 $messageparams[] = $userid;
1563 if (!is_null($conversationid)) {
1564 $messagesql .= " AND mc.id = ?";
1565 $messageparams[] = $conversationid;
79f6c36c
MN
1566 }
1567
74ad60bf
MN
1568 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
1569 foreach ($messages as $message) {
1570 self::mark_message_as_read($userid, $message);
1571 }
1572 $messages->close();
1573 }
1574
1575 /**
1576 * Marks all notifications being sent from one user to another user as read.
1577 *
1578 * If the from user is null then it marks all notifications as read sent to the to user.
1579 *
1580 * @param int $touserid the id of the message recipient
1581 * @param int|null $fromuserid the id of the message sender, null if all messages
1582 * @return void
1583 */
1584 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
1585 global $DB;
1586
883ce421
MN
1587 $notificationsql = "SELECT n.*
1588 FROM {notifications} n
74ad60bf
MN
1589 WHERE useridto = ?
1590 AND timeread is NULL";
883ce421 1591 $notificationsparams = [$touserid];
79f6c36c 1592 if (!empty($fromuserid)) {
883ce421
MN
1593 $notificationsql .= " AND useridfrom = ?";
1594 $notificationsparams[] = $fromuserid;
79f6c36c
MN
1595 }
1596
74ad60bf
MN
1597 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
1598 foreach ($notifications as $notification) {
1599 self::mark_notification_as_read($notification);
79f6c36c 1600 }
74ad60bf
MN
1601 $notifications->close();
1602 }
79f6c36c 1603
74ad60bf
MN
1604 /**
1605 * Marks ALL messages being sent from $fromuserid to $touserid as read.
1606 *
1607 * Can be filtered by type.
1608 *
1609 * @deprecated since 3.5
1610 * @param int $touserid the id of the message recipient
1611 * @param int $fromuserid the id of the message sender
1612 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
1613 * @return void
1614 */
1615 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
1616 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
1617 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
1618 DEBUG_DEVELOPER);
1619
1620 $type = strtolower($type);
1621
1622 $conversationid = null;
1623 $ignoremessages = false;
1624 if (!empty($fromuserid)) {
99248f61 1625 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
74ad60bf
MN
1626 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
1627 $ignoremessages = true;
1628 }
79f6c36c
MN
1629 }
1630
74ad60bf
MN
1631 if (!empty($type)) {
1632 if ($type == MESSAGE_TYPE_NOTIFICATION) {
99248f61 1633 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf
MN
1634 } else if ($type == MESSAGE_TYPE_MESSAGE) {
1635 if (!$ignoremessages) {
99248f61 1636 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf
MN
1637 }
1638 }
1639 } else { // We want both.
99248f61 1640 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf 1641 if (!$ignoremessages) {
99248f61 1642 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf 1643 }
883ce421 1644 }
79f6c36c
MN
1645 }
1646
79f6c36c
MN
1647 /**
1648 * Returns message preferences.
1649 *
1650 * @param array $processors
1651 * @param array $providers
1652 * @param \stdClass $user
1653 * @return \stdClass
1654 * @since 3.2
1655 */
1656 public static function get_all_message_preferences($processors, $providers, $user) {
1657 $preferences = helper::get_providers_preferences($providers, $user->id);
1658 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
1659
1660 // For every processors put its options on the form (need to get function from processor's lib.php).
1661 foreach ($processors as $processor) {
1662 $processor->object->load_data($preferences, $user->id);
1663 }
1664
1665 // Load general messaging preferences.
f7dfa9ba 1666 $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
79f6c36c
MN
1667 $preferences->mailformat = $user->mailformat;
1668 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
1669
1670 return $preferences;
1671 }
5b0769db
MN
1672
1673 /**
1674 * Count the number of users blocked by a user.
1675 *
1676 * @param \stdClass $user The user object
1677 * @return int the number of blocked users
1678 */
1679 public static function count_blocked_users($user = null) {
1680 global $USER, $DB;
1681
1682 if (empty($user)) {
1683 $user = $USER;
1684 }
1685
f219eac7
MN
1686 $sql = "SELECT count(mub.id)
1687 FROM {message_users_blocked} mub
1688 WHERE mub.userid = :userid";
5b0769db
MN
1689 return $DB->count_records_sql($sql, array('userid' => $user->id));
1690 }
1691
1692 /**
1693 * Determines if a user is permitted to send another user a private message.
1694 * If no sender is provided then it defaults to the logged in user.
1695 *
1696 * @param \stdClass $recipient The user object.
1697 * @param \stdClass|null $sender The user object.
1698 * @return bool true if user is permitted, false otherwise.
1699 */
1700 public static function can_post_message($recipient, $sender = null) {
1701 global $USER;
1702
1703 if (is_null($sender)) {
1704 // The message is from the logged in user, unless otherwise specified.
1705 $sender = $USER;
1706 }
1707
7983fb83
SA
1708 $systemcontext = \context_system::instance();
1709 if (!has_capability('moodle/site:sendmessage', $systemcontext, $sender)) {
5b0769db
MN
1710 return false;
1711 }
1712
7983fb83 1713 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender->id)) {
c886e2c9
MN
1714 return true;
1715 }
1716
7983fb83 1717 // Check if the recipient can be messaged by the sender.
9f82758c 1718 return (self::can_contact_user($recipient->id, $sender->id));
5b0769db
MN
1719 }
1720
8e3bf150
JD
1721 /**
1722 * Determines if a user is permitted to send a message to a given conversation.
1723 * If no sender is provided then it defaults to the logged in user.
1724 *
1725 * @param int $userid the id of the user on which the checks will be applied.
1726 * @param int $conversationid the id of the conversation we wish to check.
1727 * @return bool true if the user can send a message to the conversation, false otherwise.
1728 * @throws \moodle_exception
1729 */
1730 public static function can_send_message_to_conversation(int $userid, int $conversationid) : bool {
1731 global $DB;
1732
1733 $systemcontext = \context_system::instance();
1734 if (!has_capability('moodle/site:sendmessage', $systemcontext, $userid)) {
1735 return false;
1736 }
1737
1738 if (!self::is_user_in_conversation($userid, $conversationid)) {
1739 return false;
1740 }
1741
1742 // User can post messages and is in the conversation, but we need to check the conversation type to
1743 // know whether or not to check the user privacy settings via can_contact_user().
1744 $conversation = $DB->get_record('message_conversations', ['id' => $conversationid], '*', MUST_EXIST);
1745 if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
1746 return true;
1747 } else if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1748 // Get the other user in the conversation.
1749 $members = self::get_conversation_members($userid, $conversationid);
1750 $otheruser = array_filter($members, function($member) use($userid) {
1751 return $member->id != $userid;
1752 });
1753 $otheruser = reset($otheruser);
1754
9f82758c 1755 return self::can_contact_user($otheruser->id, $userid);
8e3bf150
JD
1756 } else {
1757 throw new \moodle_exception("Invalid conversation type '$conversation->type'.");
1758 }
1759 }
1760
52f9cf20
JD
1761 /**
1762 * Send a message from a user to a conversation.
1763 *
1764 * This method will create the basic eventdata and delegate to message creation to message_send.
1765 * The message_send() method is responsible for event data that is specific to each recipient.
1766 *
1767 * @param int $userid the sender id.
1768 * @param int $conversationid the conversation id.
1769 * @param string $message the message to send.
1770 * @param int $format the format of the message to send.
1771 * @return \stdClass the message created.
1772 * @throws \coding_exception
1773 * @throws \moodle_exception if the user is not permitted to send a message to the conversation.
1774 */
1775 public static function send_message_to_conversation(int $userid, int $conversationid, string $message,
1776 int $format) : \stdClass {
1777 global $DB;
1778
1779 if (!self::can_send_message_to_conversation($userid, $conversationid)) {
1780 throw new \moodle_exception("User $userid cannot send a message to conversation $conversationid");
1781 }
1782
1783 $eventdata = new \core\message\message();
1784 $eventdata->courseid = 1;
1785 $eventdata->component = 'moodle';
1786 $eventdata->name = 'instantmessage';
1787 $eventdata->userfrom = $userid;
1788 $eventdata->convid = $conversationid;
1789
1790 if ($format == FORMAT_HTML) {
1791 $eventdata->fullmessagehtml = $message;
1792 // Some message processors may revert to sending plain text even if html is supplied,
1793 // so we keep both plain and html versions if we're intending to send html.
1794 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
1795 } else {
1796 $eventdata->fullmessage = $message;
1797 $eventdata->fullmessagehtml = '';
1798 }
1799
1800 $eventdata->fullmessageformat = $format;
1801 $eventdata->smallmessage = $message; // Store the message unfiltered. Clean up on output.
1802
1803 $eventdata->timecreated = time();
1804 $eventdata->notification = 0;
1805 $messageid = message_send($eventdata);
1806
1807 $messagerecord = $DB->get_record('messages', ['id' => $messageid], 'id, useridfrom, fullmessage, timecreated');
1808 $message = (object) [
1809 'id' => $messagerecord->id,
1810 'useridfrom' => $messagerecord->useridfrom,
1811 'text' => $messagerecord->fullmessage,
1812 'timecreated' => $messagerecord->timecreated
1813 ];
1814 return $message;
5b0769db
MN
1815 }
1816
f7dfa9ba
SA
1817 /**
1818 * Get the messaging preference for a user.
1819 * If the user has not any messaging privacy preference:
1820 * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
1821 * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
1822 *
1823 * @param int $userid The user identifier.
1824 * @return int The default messaging preference.
1825 */
1826 public static function get_user_privacy_messaging_preference(int $userid) : int {
d3d95d5d 1827 global $CFG, $USER;
f7dfa9ba
SA
1828
1829 // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
1830 // otherwise, the default value will be "My contacts and anyone in my courses".
1831 if (empty($CFG->messagingallusers)) {
1832 $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
1833 } else {
1834 $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
1835 }
d3d95d5d
RW
1836 if ($userid == $USER->id) {
1837 $user = $USER;
1838 } else {
1839 $user = $userid;
1840 }
1841 $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $user);
f7dfa9ba
SA
1842
1843 // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
1844 // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1845 if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
1846 $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
1847 }
1848
1849 return $privacypreference;
1850 }
1851
5b0769db
MN
1852 /**
1853 * Checks if the recipient is allowing messages from users that aren't a
1854 * contact. If not then it checks to make sure the sender is in the
1855 * recipient's contacts.
1856 *
e5eba802 1857 * @deprecated since 3.6
5b0769db
MN
1858 * @param \stdClass $recipient The user object.
1859 * @param \stdClass|null $sender The user object.
1860 * @return bool true if $sender is blocked, false otherwise.
1861 */
1862 public static function is_user_non_contact_blocked($recipient, $sender = null) {
e5eba802
SA
1863 debugging('\core_message\api::is_user_non_contact_blocked() is deprecated', DEBUG_DEVELOPER);
1864
f7dfa9ba 1865 global $USER, $CFG;
5b0769db
MN
1866
1867 if (is_null($sender)) {
1868 // The message is from the logged in user, unless otherwise specified.
1869 $sender = $USER;
1870 }
1871
f7dfa9ba
SA
1872 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1873 switch ($privacypreference) {
1874 case self::MESSAGE_PRIVACY_SITE:
1875 if (!empty($CFG->messagingallusers)) {
1876 // Users can be messaged without being contacts or members of the same course.
1877 break;
1878 }
1879 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1880 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1881 case self::MESSAGE_PRIVACY_COURSEMEMBER:
1882 // Confirm the sender and the recipient are both members of the same course.
1883 if (enrol_sharing_course($recipient, $sender)) {
1884 // All good, the recipient and the sender are members of the same course.
1885 return false;
1886 }
1887 case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1888 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1889 return !self::is_contact($sender->id, $recipient->id);
5b0769db
MN
1890 }
1891
1892 return false;
1893 }
1894
1895 /**
1896 * Checks if the recipient has specifically blocked the sending user.
1897 *
1898 * Note: This function will always return false if the sender has the
1899 * readallmessages capability at the system context level.
1900 *
c886e2c9 1901 * @deprecated since 3.6
26dca05d
JP
1902 * @param int $recipientid User ID of the recipient.
1903 * @param int $senderid User ID of the sender.
5b0769db
MN
1904 * @return bool true if $sender is blocked, false otherwise.
1905 */
26dca05d 1906 public static function is_user_blocked($recipientid, $senderid = null) {
c886e2c9
MN
1907 debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1908 DEBUG_DEVELOPER);
1909
1910 global $USER;
5b0769db 1911
26dca05d 1912 if (is_null($senderid)) {
5b0769db 1913 // The message is from the logged in user, unless otherwise specified.
26dca05d 1914 $senderid = $USER->id;
5b0769db
MN
1915 }
1916
1917 $systemcontext = \context_system::instance();
26dca05d 1918 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
5b0769db
MN
1919 return false;
1920 }
1921
f219eac7 1922 if (self::is_blocked($recipientid, $senderid)) {
26dca05d 1923 return true;
5b0769db
MN
1924 }
1925
1926 return false;
1927 }
20ab51fd
AA
1928
1929 /**
1930 * Get specified message processor, validate corresponding plugin existence and
1931 * system configuration.
1932 *
1933 * @param string $name Name of the processor.
1934 * @param bool $ready only return ready-to-use processors.
1935 * @return mixed $processor if processor present else empty array.
1936 * @since Moodle 3.2
1937 */
1938 public static function get_message_processor($name, $ready = false) {
1939 global $DB, $CFG;
1940
1941 $processor = $DB->get_record('message_processors', array('name' => $name));
1942 if (empty($processor)) {
1943 // Processor not found, return.
1944 return array();
1945 }
1946
1947 $processor = self::get_processed_processor_object($processor);
1948 if ($ready) {
1949 if ($processor->enabled && $processor->configured) {
1950 return $processor;
1951 } else {
1952 return array();
1953 }
1954 } else {
1955 return $processor;
1956 }
1957 }
1958
1959 /**
1960 * Returns weather a given processor is enabled or not.
1961 * Note:- This doesn't check if the processor is configured or not.
1962 *
1963 * @param string $name Name of the processor
1964 * @return bool
1965 */
1966 public static function is_processor_enabled($name) {
1967
1968 $cache = \cache::make('core', 'message_processors_enabled');
1969 $status = $cache->get($name);
1970
1971 if ($status === false) {
1972 $processor = self::get_message_processor($name);
1973 if (!empty($processor)) {
1974 $cache->set($name, $processor->enabled);
1975 return $processor->enabled;
1976 } else {
1977 return false;
1978 }
1979 }
1980
1981 return $status;
1982 }
1983
1984 /**
1985 * Set status of a processor.
1986 *
1987 * @param \stdClass $processor processor record.
1988 * @param 0|1 $enabled 0 or 1 to set the processor status.
1989 * @return bool
1990 * @since Moodle 3.2
1991 */
1992 public static function update_processor_status($processor, $enabled) {
1993 global $DB;
1994 $cache = \cache::make('core', 'message_processors_enabled');
1995 $cache->delete($processor->name);
1996 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1997 }
1998
1999 /**
2000 * Given a processor object, loads information about it's settings and configurations.
2001 * This is not a public api, instead use @see \core_message\api::get_message_processor()
2002 * or @see \get_message_processors()
2003 *
2004 * @param \stdClass $processor processor object
2005 * @return \stdClass processed processor object
2006 * @since Moodle 3.2
2007 */
2008 public static function get_processed_processor_object(\stdClass $processor) {
2009 global $CFG;
2010
2011 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2012 if (is_readable($processorfile)) {
2013 include_once($processorfile);
2014 $processclass = 'message_output_' . $processor->name;
2015 if (class_exists($processclass)) {
2016 $pclass = new $processclass();
2017 $processor->object = $pclass;
2018 $processor->configured = 0;
2019 if ($pclass->is_system_configured()) {
2020 $processor->configured = 1;
2021 }
2022 $processor->hassettings = 0;
2023 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2024 $processor->hassettings = 1;
2025 }
2026 $processor->available = 1;
2027 } else {
2028 print_error('errorcallingprocessor', 'message');
2029 }
2030 } else {
2031 $processor->available = 0;
2032 }
2033 return $processor;
2034 }
883ce421
MN
2035
2036 /**
2037 * Retrieve users blocked by $user1
2038 *
2039 * @param int $userid The user id of the user whos blocked users we are returning
2040 * @return array the users blocked
2041 */
2042 public static function get_blocked_users($userid) {
2043 global $DB;
2044
2045 $userfields = \user_picture::fields('u', array('lastaccess'));
2046 $blockeduserssql = "SELECT $userfields
f219eac7 2047 FROM {message_users_blocked} mub
883ce421 2048 INNER JOIN {user} u
f219eac7 2049 ON u.id = mub.blockeduserid
883ce421 2050 WHERE u.deleted = 0
f219eac7 2051 AND mub.userid = ?
883ce421
MN
2052 GROUP BY $userfields
2053 ORDER BY u.firstname ASC";
2054 return $DB->get_records_sql($blockeduserssql, [$userid]);
2055 }
2056
2057 /**
2058 * Mark a single message as read.
2059 *
2060 * @param int $userid The user id who marked the message as read
548936a6 2061 * @param \stdClass $message The message
883ce421
MN
2062 * @param int|null $timeread The time the message was marked as read, if null will default to time()
2063 */
548936a6 2064 public static function mark_message_as_read($userid, $message, $timeread = null) {
883ce421
MN
2065 global $DB;
2066
2067 if (is_null($timeread)) {
2068 $timeread = time();
2069 }
2070
5aac33c7
MN
2071 $mua = new \stdClass();
2072 $mua->userid = $userid;
2073 $mua->messageid = $message->id;
2074 $mua->action = self::MESSAGE_ACTION_READ;
2075 $mua->timecreated = $timeread;
2076 $mua->id = $DB->insert_record('message_user_actions', $mua);
2077
2078 // Get the context for the user who received the message.
2079 $context = \context_user::instance($userid, IGNORE_MISSING);
2080 // If the user no longer exists the context value will be false, in this case use the system context.
2081 if ($context === false) {
2082 $context = \context_system::instance();
883ce421 2083 }
5aac33c7
MN
2084
2085 // Trigger event for reading a message.
2086 $event = \core\event\message_viewed::create(array(
2087 'objectid' => $mua->id,
2088 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
2089 'context' => $context,
2090 'relateduserid' => $message->useridfrom,
2091 'other' => array(
2092 'messageid' => $message->id
2093 )
2094 ));
2095 $event->trigger();
883ce421
MN
2096 }
2097
2098 /**
2099 * Mark a single notification as read.
2100 *
548936a6 2101 * @param \stdClass $notification The notification
883ce421
MN
2102 * @param int|null $timeread The time the message was marked as read, if null will default to time()
2103 */
548936a6 2104 public static function mark_notification_as_read($notification, $timeread = null) {
883ce421
MN
2105 global $DB;
2106
2107 if (is_null($timeread)) {
2108 $timeread = time();
2109 }
2110
883ce421
MN
2111 if (is_null($notification->timeread)) {
2112 $updatenotification = new \stdClass();
2113 $updatenotification->id = $notification->id;
2114 $updatenotification->timeread = $timeread;
2115
2116 $DB->update_record('notifications', $updatenotification);
376a79c2
MN
2117
2118 // Trigger event for reading a notification.
2119 \core\event\notification_viewed::create_from_ids(
2120 $notification->useridfrom,
2121 $notification->useridto,
2122 $notification->id
2123 )->trigger();
883ce421
MN
2124 }
2125 }
2126
2127 /**
2128 * Checks if a user can delete a message.
2129 *
2130 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
2131 * but will still seem as if it was by the user)
2132 * @param int $messageid The message id
2133 * @return bool Returns true if a user can delete the message, false otherwise.
2134 */
2135 public static function can_delete_message($userid, $messageid) {
2136 global $DB, $USER;
2137
08cb8a34
MN
2138 $systemcontext = \context_system::instance();
2139
2140 $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
2141
2142 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
2143 return true;
883ce421
MN
2144 }
2145
08cb8a34
MN
2146 if (!self::is_user_in_conversation($userid, $conversationid)) {
2147 return false;
2148 }
883ce421 2149
08cb8a34
MN
2150 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
2151 $USER->id == $userid) {
883ce421
MN
2152 return true;
2153 }
2154
2155 return false;
2156 }
2157
2158 /**
2159 * Deletes a message.
2160 *
2161 * This function does not verify any permissions.
2162 *
2163 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
2164 * but will still seem as if it was by the user)
2165 * @param int $messageid The message id
2166 * @return bool
2167 */
2168 public static function delete_message($userid, $messageid) {
14de10c4 2169 global $DB, $USER;
883ce421 2170
14de10c4
MN
2171 if (!$DB->record_exists('messages', ['id' => $messageid])) {
2172 return false;
2173 }
883ce421
MN
2174
2175 // Check if the user has already deleted this message.
2176 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
2177 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
2178 $mua = new \stdClass();
2179 $mua->userid = $userid;
2180 $mua->messageid = $messageid;
2181 $mua->action = self::MESSAGE_ACTION_DELETED;
2182 $mua->timecreated = time();
2183 $mua->id = $DB->insert_record('message_user_actions', $mua);
2184
2185 // Trigger event for deleting a message.
14de10c4
MN
2186 \core\event\message_deleted::create_from_ids($userid, $USER->id,
2187 $messageid, $mua->id)->trigger();
883ce421
MN
2188
2189 return true;
2190 }
2191
2192 return false;
2193 }
2194
2195 /**
2196 * Returns the conversation between two users.
2197 *
b2cd17e6 2198 * @param array $userids
883ce421
MN
2199 * @return int|bool The id of the conversation, false if not found
2200 */
b2cd17e6 2201 public static function get_conversation_between_users(array $userids) {
883ce421
MN
2202 global $DB;
2203
0866b336
RW
2204 $conversations = self::get_individual_conversations_between_users([$userids]);
2205 $conversation = $conversations[0];
883ce421 2206
0866b336 2207 if ($conversation) {
883ce421
MN
2208 return $conversation->id;
2209 }
2210
2211 return false;
2212 }
2213
0866b336
RW
2214 /**
2215 * Returns the conversations between sets of users.
2216 *
2217 * The returned array of results will be in the same order as the requested
2218 * arguments, null will be returned if there is no conversation for that user
2219 * pair.
2220 *
2221 * For example:
2222 * If we have 6 users with ids 1, 2, 3, 4, 5, 6 where only 2 conversations
2223 * exist. One between 1 and 2 and another between 5 and 6.
2224 *
2225 * Then if we call:
2226 * $conversations = get_individual_conversations_between_users([[1,2], [3,4], [5,6]]);
2227 *
2228 * The conversations array will look like:
2229 * [<conv_record>, null, <conv_record>];
2230 *
2231 * Where null is returned for the pairing of [3, 4] since no record exists.
2232 *
2233 * @param array $useridsets An array of arrays where the inner array is the set of user ids
2234 * @return stdClass[] Array of conversation records
2235 */
2236 public static function get_individual_conversations_between_users(array $useridsets) : array {
2237 global $DB;
2238
2239 if (empty($useridsets)) {
2240 return [];
2241 }
2242
2243 $hashes = array_map(function($userids) {
2244 return helper::get_conversation_hash($userids);
2245 }, $useridsets);
2246
2247 list($inorequalsql, $params) = $DB->get_in_or_equal($hashes);
2248 array_unshift($params, self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL);
2249 $where = "type = ? AND convhash ${inorequalsql}";
2250 $conversations = array_fill(0, count($hashes), null);
2251 $records = $DB->get_records_select('message_conversations', $where, $params);
2252
2253 foreach (array_values($records) as $record) {
2254 $index = array_search($record->convhash, $hashes);
2255 if ($index !== false) {
2256 $conversations[$index] = $record;
2257 }
2258 }
2259
2260 return $conversations;
2261 }
2262
883ce421
MN
2263 /**
2264 * Creates a conversation between two users.
2265 *
a66ae849 2266 * @deprecated since 3.6
b2cd17e6 2267 * @param array $userids
883ce421
MN
2268 * @return int The id of the conversation
2269 */
b2cd17e6 2270 public static function create_conversation_between_users(array $userids) {
a66ae849
MN
2271 debugging('\core_message\api::create_conversation_between_users is deprecated, please use ' .
2272 '\core_message\api::create_conversation instead.', DEBUG_DEVELOPER);
2273
f2ac0a3e
MN
2274 // This method was always used for individual conversations.
2275 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
2276
2277 return $conversation->id;
2278 }
2279
2280 /**
2281 * Creates a conversation with selected users and messages.
2282 *
2283 * @param int $type The type of conversation
2284 * @param int[] $userids The array of users to add to the conversation
76540bec
MN
2285 * @param string|null $name The name of the conversation
2286 * @param int $enabled Determines if the conversation is created enabled or disabled
2287 * @param string|null $component Defines the Moodle component which the conversation belongs to, if any
2288 * @param string|null $itemtype Defines the type of the component
2289 * @param int|null $itemid The id of the component
2290 * @param int|null $contextid The id of the context
f2ac0a3e
MN
2291 * @return \stdClass
2292 */
76540bec
MN
2293 public static function create_conversation(int $type, array $userids, string $name = null,
2294 int $enabled = self::MESSAGE_CONVERSATION_ENABLED, string $component = null,
2295 string $itemtype = null, int $itemid = null, int $contextid = null) {
2296
883ce421
MN
2297 global $DB;
2298
869eac82
MN
2299 $validtypes = [
2300 self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2301 self::MESSAGE_CONVERSATION_TYPE_GROUP
2302 ];
2303
2304 if (!in_array($type, $validtypes)) {
2305 throw new \moodle_exception('An invalid conversation type was specified.');
2306 }
2307
f2ac0a3e
MN
2308 // Sanity check.
2309 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
2310 if (count($userids) > 2) {
2311 throw new \moodle_exception('An individual conversation can not have more than two users.');
2312 }
2313 }
2314
883ce421 2315 $conversation = new \stdClass();
f2ac0a3e
MN
2316 $conversation->type = $type;
2317 $conversation->name = $name;
2318 $conversation->convhash = null;
2319 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
2320 $conversation->convhash = helper::get_conversation_hash($userids);
2321 }
76540bec
MN
2322 $conversation->component = $component;
2323 $conversation->itemtype = $itemtype;
2324 $conversation->itemid = $itemid;
2325 $conversation->contextid = $contextid;
2326 $conversation->enabled = $enabled;
883ce421 2327 $conversation->timecreated = time();
76540bec 2328 $conversation->timemodified = $conversation->timecreated;
883ce421
MN
2329 $conversation->id = $DB->insert_record('message_conversations', $conversation);
2330
f2ac0a3e
MN
2331 // Add users to this conversation.
2332 $arrmembers = [];
b2cd17e6
MN
2333 foreach ($userids as $userid) {
2334 $member = new \stdClass();
2335 $member->conversationid = $conversation->id;
2336 $member->userid = $userid;
2337 $member->timecreated = time();
f2ac0a3e
MN
2338 $member->id = $DB->insert_record('message_conversation_members', $member);
2339
2340 $arrmembers[] = $member;
b2cd17e6 2341 }
883ce421 2342
f2ac0a3e
MN
2343 $conversation->members = $arrmembers;
2344
2345 return $conversation;
883ce421 2346 }
0b3eadcd 2347
e66b915c
MN
2348 /**
2349 * Checks if a user can create a group conversation.
2350 *
2351 * @param int $userid The id of the user attempting to create the conversation
2352 * @param \context $context The context they are creating the conversation from, most likely course context
2353 * @return bool
2354 */
2355 public static function can_create_group_conversation(int $userid, \context $context) : bool {
2356 global $CFG;
2357
2358 // If we can't message at all, then we can't create a conversation.
2359 if (empty($CFG->messaging)) {
2360 return false;
2361 }
2362
2363 // We need to check they have the capability to create the conversation.
2364 return has_capability('moodle/course:creategroupconversations', $context, $userid);
883ce421 2365 }
0b3eadcd 2366
0d203bbf
MN
2367 /**
2368 * Checks if a user can create a contact request.
2369 *
2370 * @param int $userid The id of the user who is creating the contact request
2371 * @param int $requesteduserid The id of the user being requested
2372 * @return bool
2373 */
2374 public static function can_create_contact(int $userid, int $requesteduserid) : bool {
2375 global $CFG;
2376
2377 // If we can't message at all, then we can't create a contact.
2378 if (empty($CFG->messaging)) {
2379 return false;
2380 }
2381
2382 // If we can message anyone on the site then we can create a contact.
2383 if ($CFG->messagingallusers) {
2384 return true;
2385 }
2386
2387 // We need to check if they are in the same course.
2388 return enrol_sharing_course($userid, $requesteduserid);
2389 }
2390
0b3eadcd
MN
2391 /**
2392 * Handles creating a contact request.
2393 *
2394 * @param int $userid The id of the user who is creating the contact request
2395 * @param int $requesteduserid The id of the user being requested
0866b336 2396 * @return \stdClass the request
0b3eadcd 2397 */
0866b336 2398 public static function create_contact_request(int $userid, int $requesteduserid) : \stdClass {
0b3eadcd
MN
2399 global $DB;
2400
2401 $request = new \stdClass();
2402 $request->userid = $userid;
2403 $request->requesteduserid = $requesteduserid;
2404 $request->timecreated = time();
2405
0866b336
RW
2406 $request->id = $DB->insert_record('message_contact_requests', $request);
2407
2408 return $request;
0b3eadcd
MN
2409 }
2410
2411
2412 /**
2413 * Handles confirming a contact request.
2414 *
2415 * @param int $userid The id of the user who created the contact request
2416 * @param int $requesteduserid The id of the user confirming the request
2417 */
2418 public static function confirm_contact_request(int $userid, int $requesteduserid) {
2419 global $DB;
2420
2421 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2422 'requesteduserid' => $requesteduserid])) {
2423 self::add_contact($userid, $requesteduserid);
2424
2425 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2426 }
2427 }
2428
2429 /**
2430 * Handles declining a contact request.
2431 *
2432 * @param int $userid The id of the user who created the contact request
2433 * @param int $requesteduserid The id of the user declining the request
2434 */
2435 public static function decline_contact_request(int $userid, int $requesteduserid) {
2436 global $DB;
2437
2438 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2439 'requesteduserid' => $requesteduserid])) {
2440 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2441 }
2442 }
2443
2444 /**
2445 * Handles returning the contact requests for a user.
2446 *
2447 * This also includes the user data necessary to display information
2448 * about the user.
2449 *
2450 * It will not include blocked users.
2451 *
2452 * @param int $userid
accd6482
MN
2453 * @param int $limitfrom
2454 * @param int $limitnum
0b3eadcd
MN
2455 * @return array The list of contact requests
2456 */
accd6482 2457 public static function get_contact_requests(int $userid, int $limitfrom = 0, int $limitnum = 0) : array {
0b3eadcd
MN
2458 global $DB;
2459
daa33803
MN
2460 $sql = "SELECT mcr.userid
2461 FROM {message_contact_requests} mcr
0b3eadcd 2462 LEFT JOIN {message_users_blocked} mub
daa33803 2463 ON (mub.userid = ? AND mub.blockeduserid = mcr.userid)
0b3eadcd 2464 WHERE mcr.requesteduserid = ?
0b3eadcd 2465 AND mub.id is NULL
accd6482
MN
2466 ORDER BY mcr.timecreated ASC";
2467 if ($contactrequests = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
daa33803
MN
2468 $userids = array_keys($contactrequests);
2469 return helper::get_member_info($userid, $userids);
2470 }
0b3eadcd 2471
daa33803 2472 return [];
0b3eadcd
MN
2473 }
2474
0866b336
RW
2475 /**
2476 * Count how many contact requests the user has received.
2477 *
2478 * @param \stdClass $user The user to fetch contact requests for
2479 * @return int The count
2480 */
2481 public static function count_received_contact_requests(\stdClass $user) : int {
2482 global $DB;
2483 return $DB->count_records('message_contact_requests', ['requesteduserid' => $user->id]);
2484 }
2485
0b3eadcd
MN
2486 /**
2487 * Handles adding a contact.
2488 *
2489 * @param int $userid The id of the user who requested to be a contact
2490 * @param int $contactid The id of the contact
2491 */
2492 public static function add_contact(int $userid, int $contactid) {
2493 global $DB;
2494
2495 $messagecontact = new \stdClass();
2496 $messagecontact->userid = $userid;
2497 $messagecontact->contactid = $contactid;
2498 $messagecontact->timecreated = time();
2499 $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
2500
2501 $eventparams = [
2502 'objectid' => $messagecontact->id,
2503 'userid' => $userid,
2504 'relateduserid' => $contactid,
2505 'context' => \context_user::instance($userid)
2506 ];
2507 $event = \core\event\message_contact_added::create($eventparams);
2508 $event->add_record_snapshot('message_contacts', $messagecontact);
2509 $event->trigger();
2510 }
2511
2512 /**
2513 * Handles removing a contact.
2514 *
2515 * @param int $userid The id of the user who is removing a user as a contact
2516 * @param int $contactid The id of the user to be removed as a contact
2517 */
2518 public static function remove_contact(int $userid, int $contactid) {
2519 global $DB;
2520
2521 if ($contact = self::get_contact($userid, $contactid)) {
2522 $DB->delete_records('message_contacts', ['id' => $contact->id]);
2523
2524 $event = \core\event\message_contact_removed::create(array(
2525 'objectid' => $contact->id,
2526 'userid' => $userid,
2527 'relateduserid' => $contactid,
2528 'context' => \context_user::instance($userid)
2529 ));
2530 $event->add_record_snapshot('message_contacts', $contact);
2531 $event->trigger();
2532 }
2533 }
2534
2535 /**
2536 * Handles blocking a user.
2537 *
2538 * @param int $userid The id of the user who is blocking
2539 * @param int $usertoblockid The id of the user being blocked
2540 */
2541 public static function block_user(int $userid, int $usertoblockid) {
2542 global $DB;
2543
2544 $blocked = new \stdClass();
2545 $blocked->userid = $userid;
2546 $blocked->blockeduserid = $usertoblockid;
2547 $blocked->timecreated = time();
2548 $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
2549
2550 // Trigger event for blocking a contact.
2551 $event = \core\event\message_user_blocked::create(array(
2552 'objectid' => $blocked->id,
2553 'userid' => $userid,
2554 'relateduserid' => $usertoblockid,
2555 'context' => \context_user::instance($userid)
2556 ));
2557 $event->add_record_snapshot('message_users_blocked', $blocked);
2558 $event->trigger();
2559 }
2560
2561 /**
2562 * Handles unblocking a user.
2563 *
2564 * @param int $userid The id of the user who is unblocking
2565 * @param int $usertounblockid The id of the user being unblocked
2566 */
2567 public static function unblock_user(int $userid, int $usertounblockid) {
2568 global $DB;
2569
2570 if ($blockeduser = $DB->get_record('message_users_blocked',
2571 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
2572 $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
2573
2574 // Trigger event for unblocking a contact.
2575 $event = \core\event\message_user_unblocked::create(array(
2576 'objectid' => $blockeduser->id,
2577 'userid' => $userid,
2578 'relateduserid' => $usertounblockid,
2579 'context' => \context_user::instance($userid)
2580 ));
2581 $event->add_record_snapshot('message_users_blocked', $blockeduser);
2582 $event->trigger();
2583 }
2584 }
2585
2586 /**
2587 * Checks if users are already contacts.
2588 *
2589 * @param int $userid The id of one of the users
2590 * @param int $contactid The id of the other user
2591 * @return bool Returns true if they are a contact, false otherwise
2592 */
2593 public static function is_contact(int $userid, int $contactid) : bool {
2594 global $DB;
2595
2596 $sql = "SELECT id
2597 FROM {message_contacts} mc
2598 WHERE (mc.userid = ? AND mc.contactid = ?)
2599 OR (mc.userid = ? AND mc.contactid = ?)";
2600 return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
2601 }
2602
2603 /**
2604 * Returns the row in the database table message_contacts that represents the contact between two people.
2605 *
2606 * @param int $userid The id of one of the users
2607 * @param int $contactid The id of the other user
2608 * @return mixed A fieldset object containing the record, false otherwise
2609 */
2610 public static function get_contact(int $userid, int $contactid) {
2611 global $DB;
2612
2613 $sql = "SELECT mc.*
2614 FROM {message_contacts} mc
2615 WHERE (mc.userid = ? AND mc.contactid = ?)
2616 OR (mc.userid = ? AND mc.contactid = ?)";
2617 return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
2618 }
2619
2620 /**
2621 * Checks if a user is already blocked.
2622 *
0b3eadcd
MN
2623 * @param int $userid
2624 * @param int $blockeduserid
2625 * @return bool Returns true if they are a blocked, false otherwise
2626 */
2627 public static function is_blocked(int $userid, int $blockeduserid) : bool {
2628 global $DB;
2629
2630 return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
2631 }
2632
0866b336
RW
2633 /**
2634 * Get contact requests between users.
2635 *
2636 * @param int $userid The id of the user who is creating the contact request
2637 * @param int $requesteduserid The id of the user being requested
2638 * @return \stdClass[]
2639 */
2640 public static function get_contact_requests_between_users(int $userid, int $requesteduserid) : array {
2641 global $DB;
2642
2643 $sql = "SELECT *
2644 FROM {message_contact_requests} mcr
2645 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
2646 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
2647 return $DB->get_records_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
2648 }
2649
0b3eadcd
MN
2650 /**
2651 * Checks if a contact request already exists between users.
2652 *
2653 * @param int $userid The id of the user who is creating the contact request
2654 * @param int $requesteduserid The id of the user being requested
2655 * @return bool Returns true if a contact request exists, false otherwise
2656 */
2657 public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
2658 global $DB;
2659
2660 $sql = "SELECT id
2661 FROM {message_contact_requests} mcr
2662 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
2663 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
2664 return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
2665 }
08cb8a34
MN
2666
2667 /**
2668 * Checks if a user is already in a conversation.
2669 *
2670 * @param int $userid The id of the user we want to check if they are in a group
2671 * @param int $conversationid The id of the conversation
2672 * @return bool Returns true if a contact request exists, false otherwise
2673 */
2674 public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
2675 global $DB;
2676
2677 return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
2678 'userid' => $userid]);
7983fb83
SA
2679 }
2680
2681 /**
2682 * Checks if the sender can message the recipient.
2683 *
9f82758c
JD
2684 * @param int $recipientid
2685 * @param int $senderid
7983fb83
SA
2686 * @return bool true if recipient hasn't blocked sender and sender can contact to recipient, false otherwise.
2687 */
9f82758c
JD
2688 protected static function can_contact_user(int $recipientid, int $senderid) : bool {
2689 if (has_capability('moodle/site:messageanyuser', \context_system::instance(), $senderid)) {
7983fb83
SA
2690 // The sender has the ability to contact any user across the entire site.
2691 return true;
2692 }
2693
2694 // The initial value of $cancontact is null to indicate that a value has not been determined.
2695 $cancontact = null;
2696
9f82758c 2697 if (self::is_blocked($recipientid, $senderid)) {
7983fb83
SA
2698 // The recipient has specifically blocked this sender.
2699 $cancontact = false;
2700 }
2701
2702 $sharedcourses = null;
2703 if (null === $cancontact) {
2704 // There are three user preference options:
2705 // - Site: Allow anyone not explicitly blocked to contact me;
2706 // - Course members: Allow anyone I am in a course with to contact me; and
2707 // - Contacts: Only allow my contacts to contact me.
2708 //
2709 // The Site option is only possible when the messagingallusers site setting is also enabled.
2710
9f82758c 2711 $privacypreference = self::get_user_privacy_messaging_preference($recipientid);
7983fb83
SA
2712 if (self::MESSAGE_PRIVACY_SITE === $privacypreference) {
2713 // The user preference is to allow any user to contact them.
2714 // No need to check anything else.
2715 $cancontact = true;
2716 } else {
2717 // This user only allows their own contacts, and possibly course peers, to contact them.
2718 // If the users are contacts then we can avoid the more expensive shared courses check.
9f82758c 2719 $cancontact = self::is_contact($senderid, $recipientid);
7983fb83
SA
2720
2721 if (!$cancontact && self::MESSAGE_PRIVACY_COURSEMEMBER === $privacypreference) {
2722 // The users are not contacts and the user allows course member messaging.
2723 // Check whether these two users share any course together.
9f82758c 2724 $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
7983fb83
SA
2725 $cancontact = (!empty($sharedcourses));
2726 }
2727 }
2728 }
2729
2730 if (false === $cancontact) {
2731 // At the moment the users cannot contact one another.
2732 // Check whether the messageanyuser capability applies in any of the shared courses.
2733 // This is intended to allow teachers to message students regardless of message settings.
2734
2735 // Note: You cannot use empty($sharedcourses) here because this may be an empty array.
2736 if (null === $sharedcourses) {
9f82758c 2737 $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
7983fb83
SA
2738 }
2739
2740 foreach ($sharedcourses as $course) {
2741 // Note: enrol_get_shared_courses will preload any shared context.
9f82758c 2742 if (has_capability('moodle/site:messageanyuser', \context_course::instance($course->id), $senderid)) {
7983fb83
SA
2743 $cancontact = true;
2744 break;
2745 }
2746 }
2747 }
08cb8a34 2748
7983fb83 2749 return $cancontact;
08cb8a34 2750 }
67b81351 2751
623048af
AA
2752 /**
2753 * Add some new members to an existing conversation.
2754 *
2755 * @param array $userids User ids array to add as members.
2756 * @param int $convid The conversation id. Must exists.
2757 * @throws \dml_missing_record_exception If convid conversation doesn't exist
2758 * @throws \dml_exception If there is a database error
83e3a4fe 2759 * @throws \moodle_exception If trying to add a member(s) to a non-group conversation
623048af
AA
2760 */
2761 public static function add_members_to_conversation(array $userids, int $convid) {
2762 global $DB;
2763
2764 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2765
83e3a4fe
MN
2766 // We can only add members to a group conversation.
2767 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2768 throw new \moodle_exception('You can not add members to a non-group conversation.');
2769 }
2770
623048af
AA
2771 // Be sure we are not trying to add a non existing user to the conversation. Work only with existing users.
2772 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
4abe3d25 2773 $existingusers = $DB->get_fieldset_select('user', 'id', "id $useridcondition", $params);
623048af
AA
2774
2775 // Be sure we are not adding a user is already member of the conversation. Take all the members.
2776 $memberuserids = array_values($DB->get_records_menu(
2777 'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
2778 );
2779
2780 // Work with existing new members.
2781 $members = array();
2782 $newuserids = array_diff($existingusers, $memberuserids);
2783 foreach ($newuserids as $userid) {
2784 $member = new \stdClass();
2785 $member->conversationid = $convid;
2786 $member->userid = $userid;
2787 $member->timecreated = time();
2788 $members[] = $member;
2789 }
2790
623048af 2791 $DB->insert_records('message_conversation_members', $members);
623048af
AA
2792 }
2793
2794 /**
2795 * Remove some members from an existing conversation.
2796 *
2797 * @param array $userids The user ids to remove from conversation members.
2798 * @param int $convid The conversation id. Must exists.
2799 * @throws \dml_exception
83e3a4fe 2800 * @throws \moodle_exception If trying to remove a member(s) from a non-group conversation
623048af
AA
2801 */
2802 public static function remove_members_from_conversation(array $userids, int $convid) {
2803 global $DB;
2804
2805 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2806
83e3a4fe
MN
2807 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2808 throw new \moodle_exception('You can not remove members from a non-group conversation.');
2809 }
2810
623048af
AA
2811 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2812 $params['convid'] = $convid;
2813
623048af
AA
2814 $DB->delete_records_select('message_conversation_members',
2815 "conversationid = :convid AND userid $useridcondition", $params);
623048af
AA
2816 }
2817
2818 /**
2819 * Count conversation members.
2820 *
2821 * @param int $convid The conversation id.
2822 * @return int Number of conversation members.
2823 * @throws \dml_exception
2824 */
2825 public static function count_conversation_members(int $convid) : int {
2826 global $DB;
08cb8a34 2827
623048af 2828 return $DB->count_records('message_conversation_members', ['conversationid' => $convid]);
08cb8a34 2829 }
55fda006 2830
f0e137c5
MN
2831 /**
2832 * Checks whether or not a conversation area is enabled.
2833 *
2834 * @param string $component Defines the Moodle component which the area was added to.
2835 * @param string $itemtype Defines the type of the component.
2836 * @param int $itemid The id of the component.
2837 * @param int $contextid The id of the context.
2838 * @return bool Returns if a conversation area exists and is enabled, false otherwise
2839 */
2840 public static function is_conversation_area_enabled(string $component, string $itemtype, int $itemid, int $contextid) : bool {
2841 global $DB;
2842
76540bec 2843 return $DB->record_exists('message_conversations',
f0e137c5
MN
2844 [
2845 'itemid' => $itemid,
2846 'contextid' => $contextid,
2847 'component' => $component,
2848 'itemtype' => $itemtype,
76540bec 2849 'enabled' => self::MESSAGE_CONVERSATION_ENABLED
f0e137c5
MN
2850 ]
2851 );
2852 }
2853
e7f46714 2854 /**
76540bec 2855 * Get conversation by area.
e7f46714 2856 *
2857 * @param string $component Defines the Moodle component which the area was added to.
2858 * @param string $itemtype Defines the type of the component.
76540bec
MN
2859 * @param int $itemid The id of the component.
2860 * @param int $contextid The id of the context.
2861 * @return \stdClass
e7f46714 2862 */
76540bec 2863 public static function get_conversation_by_area(string $component, string $itemtype, int $itemid, int $contextid) {
e7f46714 2864 global $DB;
2865
76540bec 2866 return $DB->get_record('message_conversations',
f0e137c5
MN
2867 [
2868 'itemid' => $itemid,
2869 'contextid' => $contextid,
2870 'component' => $component,
2871 'itemtype' => $itemtype
2872 ]
2873 );
e7f46714 2874 }
2875
2876 /**
76540bec 2877 * Enable a conversation.
e7f46714 2878 *
76540bec 2879 * @param int $conversationid The id of the conversation.
e7f46714 2880 * @return void
2881 */
76540bec 2882 public static function enable_conversation(int $conversationid) {
e7f46714 2883 global $DB;
2884
76540bec
MN
2885 $conversation = new \stdClass();
2886 $conversation->id = $conversationid;
2887 $conversation->enabled = self::MESSAGE_CONVERSATION_ENABLED;
2888 $conversation->timemodified = time();
2889 $DB->update_record('message_conversations', $conversation);
e7f46714 2890 }
2891
2892 /**
76540bec 2893 * Disable a conversation.
e7f46714 2894 *
76540bec 2895 * @param int $conversationid The id of the conversation.
e7f46714 2896 * @return void
2897 */
76540bec 2898 public static function disable_conversation(int $conversationid) {
e7f46714 2899 global $DB;
2900
76540bec
MN
2901 $conversation = new \stdClass();
2902 $conversation->id = $conversationid;
2903 $conversation->enabled = self::MESSAGE_CONVERSATION_DISABLED;
2904 $conversation->timemodified = time();
2905 $DB->update_record('message_conversations', $conversation);
e7f46714 2906 }
2907
2908 /**
2909 * Update the name of a conversation.
2910 *
76540bec 2911 * @param int $conversationid The id of a conversation.
e7f46714 2912 * @param string $name The main name of the area
2913 * @return void
2914 */
2915 public static function update_conversation_name(int $conversationid, string $name) {
2916 global $DB;
2917
2918 if ($conversation = $DB->get_record('message_conversations', array('id' => $conversationid))) {
2919 if ($name <> $conversation->name) {
2920 $conversation->name = $name;
f0e137c5 2921 $conversation->timemodified = time();
e7f46714 2922 $DB->update_record('message_conversations', $conversation);
2923 }
2924 }
2925 }
6ecd6e5b
MN
2926
2927 /**
2928 * Returns a list of conversation members.
2929 *
2930 * @param int $userid The user we are returning the conversation members for, used by helper::get_member_info.
2931 * @param int $conversationid The id of the conversation
2932 * @param bool $includecontactrequests Do we want to include contact requests with this data?
663ccd58 2933 * @param bool $includeprivacyinfo Do we want to include privacy requests with this data?
6ecd6e5b
MN
2934 * @param int $limitfrom
2935 * @param int $limitnum
2936 * @return array
2937 */
2938 public static function get_conversation_members(int $userid, int $conversationid, bool $includecontactrequests = false,
663ccd58
RW
2939 bool $includeprivacyinfo = false, int $limitfrom = 0,
2940 int $limitnum = 0) : array {
6ecd6e5b
MN
2941 global $DB;
2942
2943 if ($members = $DB->get_records('message_conversation_members', ['conversationid' => $conversationid],
2944 'timecreated ASC, id ASC', 'userid', $limitfrom, $limitnum)) {
2945 $userids = array_keys($members);
663ccd58 2946 $members = helper::get_member_info($userid, $userids, $includecontactrequests, $includeprivacyinfo);
6ecd6e5b
MN
2947
2948 return $members;
2949 }
2950
2951 return [];
2952 }
33022ee1
JD
2953
2954 /**
2955 * Get the unread counts for all conversations for the user, sorted by type, and including favourites.
2956 *
2957 * @param int $userid the id of the user whose conversations we'll check.
2958 * @return array the unread counts for each conversation, indexed by type.
2959 */
2960 public static function get_unread_conversation_counts(int $userid) : array {
2961 global $DB;
2962
2963 // Get all conversations the user is in, and check unread.
2964 $unreadcountssql = 'SELECT conv.id, conv.type, indcounts.unreadcount
2965 FROM {message_conversations} conv
2966 INNER JOIN (
2967 SELECT m.conversationid, count(m.id) as unreadcount
2968 FROM {messages} m
2969 INNER JOIN {message_conversations} mc
2970 ON mc.id = m.conversationid
2971 INNER JOIN {message_conversation_members} mcm
2972 ON m.conversationid = mcm.conversationid
2973 LEFT JOIN {message_user_actions} mua
2974 ON (mua.messageid = m.id AND mua.userid = ? AND
2975 (mua.action = ? OR mua.action = ?))
2976 WHERE mcm.userid = ?
2977 AND m.useridfrom != ?
2978 AND mua.id is NULL
2979 GROUP BY m.conversationid
2980 ) indcounts
2981 ON indcounts.conversationid = conv.id
2982 WHERE conv.enabled = 1';
2983
2984 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
2985 $userid, $userid]);
2986
2987 // Get favourites, so we can track these separately.
2988 $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
2989 $favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
2990 $favouriteconvids = array_flip(array_column($favouriteconversations, 'itemid'));
2991
2992 // Assemble the return array.
2993 $counts = ['favourites' => 0, 'types' => [
2994 self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL => 0,
2995 self::MESSAGE_CONVERSATION_TYPE_GROUP => 0
2996 ]];
2997 foreach ($unreadcounts as $convid => $info) {
33022ee1
JD
2998 if (isset($favouriteconvids[$convid])) {
2999 $counts['favourites']++;
a5411535 3000 continue;
33022ee1 3001 }
a5411535 3002 $counts['types'][$info->type]++;
33022ee1
JD
3003 }
3004
3005 return $counts;
3006 }
879e2bef 3007}