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