Merge branch 'MDL-63840-master' of https://github.com/lucaboesch/moodle
[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,
f219eac7
MN
103 m.smallmessage, m.timecreated, 0 as isread, $ufields, mub.id as userfrom_blocked, $ufields2,
104 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
MN
153 *
154 * @param int $userid The user id doing the searching
155 * @param int $courseid The id of the course we are searching in
156 * @param string $search The string the user is searching
157 * @param int $limitfrom
158 * @param int $limitnum
de55cb1b 159 * @return array
cd03b8d7 160 */
48e8bdba 161 public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
cd03b8d7
MN
162 global $DB;
163
164 // Get all the users in the course.
165 list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
f219eac7 166 $sql = "SELECT u.*, mub.id as isblocked
cd03b8d7 167 FROM {user} u
dd0c1403
MN
168 JOIN ($esql) je
169 ON je.id = u.id
f219eac7
MN
170 LEFT JOIN {message_users_blocked} mub
171 ON (mub.blockeduserid = u.id AND mub.userid = :userid)
cd03b8d7
MN
172 WHERE u.deleted = 0";
173 // Add more conditions.
174 $fullname = $DB->sql_fullname();
dd0c1403 175 $sql .= " AND u.id != :userid2
cd03b8d7
MN
176 AND " . $DB->sql_like($fullname, ':search', false) . "
177 ORDER BY " . $DB->sql_fullname();
dd0c1403 178 $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
cd03b8d7 179
cd03b8d7
MN
180 // Convert all the user records into contacts.
181 $contacts = array();
182 if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
183 foreach ($users as $user) {
f219eac7 184 $user->blocked = $user->isblocked ? 1 : 0;
de55cb1b 185 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
186 }
187 }
188
de55cb1b 189 return $contacts;
cd03b8d7
MN
190 }
191
192 /**
48e8bdba 193 * Handles searching for user in the message area.
cd03b8d7
MN
194 *
195 * @param int $userid The user id doing the searching
196 * @param string $search The string the user is searching
197 * @param int $limitnum
de55cb1b 198 * @return array
cd03b8d7 199 */
48e8bdba 200 public static function search_users($userid, $search, $limitnum = 0) {
cd03b8d7
MN
201 global $CFG, $DB;
202
cd03b8d7
MN
203 // Used to search for contacts.
204 $fullname = $DB->sql_fullname();
205 $ufields = \user_picture::fields('u', array('lastaccess'));
206
207 // Users not to include.
208 $excludeusers = array($userid, $CFG->siteguest);
209 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
210
211 // Ok, let's search for contacts first.
212 $contacts = array();
f219eac7 213 $sql = "SELECT $ufields, mub.id as isuserblocked
cd03b8d7
MN
214 FROM {user} u
215 JOIN {message_contacts} mc
216 ON u.id = mc.contactid
f219eac7
MN
217 LEFT JOIN {message_users_blocked} mub
218 ON (mub.userid = :userid2 AND mub.blockeduserid = u.id)
cd03b8d7
MN
219 WHERE mc.userid = :userid
220 AND u.deleted = 0
221 AND u.confirmed = 1
222 AND " . $DB->sql_like($fullname, ':search', false) . "
223 AND u.id $exclude
224 ORDER BY " . $DB->sql_fullname();
f219eac7
MN
225 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'userid2' => $userid,
226 'search' => '%' . $search . '%') + $excludeparams, 0, $limitnum)) {
cd03b8d7 227 foreach ($users as $user) {
f219eac7 228 $user->blocked = $user->isuserblocked ? 1 : 0;
de55cb1b 229 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
230 }
231 }
232
233 // Now, let's get the courses.
f3249577
AG
234 // Make sure to limit searches to enrolled courses.
235 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
cd03b8d7 236 $courses = array();
93b47710
MN
237 // Really we want the user to be able to view the participants if they have the capability
238 // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
239 // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
240 // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
442f12f8 241 if ($arrcourses = \core_course_category::search_courses(array('search' => $search), array('limit' => $limitnum),
f3249577 242 array('moodle/course:viewparticipants'))) {
cd03b8d7 243 foreach ($arrcourses as $course) {
f3249577
AG
244 if (isset($enrolledcourses[$course->id])) {
245 $data = new \stdClass();
246 $data->id = $course->id;
247 $data->shortname = $course->shortname;
248 $data->fullname = $course->fullname;
249 $courses[] = $data;
250 }
cd03b8d7
MN
251 }
252 }
253
254 // Let's get those non-contacts. Toast them gears boi.
dd0c1403
MN
255 // Note - you can only block contacts, so these users will not be blocked, so no need to get that
256 // extra detail from the database.
cd03b8d7
MN
257 $noncontacts = array();
258 $sql = "SELECT $ufields
259 FROM {user} u
260 WHERE u.deleted = 0
261 AND u.confirmed = 1
262 AND " . $DB->sql_like($fullname, ':search', false) . "
263 AND u.id $exclude
7b55aaa1
MN
264 AND u.id NOT IN (SELECT contactid
265 FROM {message_contacts}
cd03b8d7
MN
266 WHERE userid = :userid)
267 ORDER BY " . $DB->sql_fullname();
7b55aaa1 268 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
f219eac7 269 0, $limitnum)) {
cd03b8d7 270 foreach ($users as $user) {
de55cb1b 271 $noncontacts[] = helper::create_contact($user);
cd03b8d7
MN
272 }
273 }
274
de55cb1b 275 return array($contacts, $courses, $noncontacts);
cd03b8d7
MN
276 }
277
eb5865da 278 /**
003cdcce 279 * Gets extra fields, like image url and subname for any conversations linked to components.
eb5865da
JD
280 *
281 * The subname is like a subtitle for the conversation, to compliment it's name.
003cdcce 282 * 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
283 *
284 * @param array $conversations a list of conversations records.
285 * @return array the array of subnames, index by conversation id.
003cdcce
JD
286 * @throws \coding_exception
287 * @throws \dml_exception
eb5865da 288 */
003cdcce 289 protected static function get_linked_conversation_extra_fields(array $conversations) : array {
eb5865da
JD
290 global $DB;
291
292 $linkedconversations = [];
293 foreach ($conversations as $conversation) {
294 if (!is_null($conversation->component) && !is_null($conversation->itemtype)) {
295 $linkedconversations[$conversation->component][$conversation->itemtype][$conversation->id]
296 = $conversation->itemid;
297 }
298 }
299 if (empty($linkedconversations)) {
300 return [];
301 }
302
303 // TODO: MDL-63814: Working out the subname for linked conversations should be done in a generic way.
304 // Get the itemid, but only for course group linked conversation for now.
003cdcce 305 $extrafields = [];
eb5865da
JD
306 if (!empty($linkeditems = $linkedconversations['core_group']['groups'])) { // Format: [conversationid => itemid].
307 // Get the name of the course to which the group belongs.
308 list ($groupidsql, $groupidparams) = $DB->get_in_or_equal(array_values($linkeditems), SQL_PARAMS_NAMED, 'groupid');
003cdcce 309 $sql = "SELECT g.*, c.shortname as courseshortname
eb5865da
JD
310 FROM {groups} g
311 JOIN {course} c
312 ON g.courseid = c.id
313 WHERE g.id $groupidsql";
314 $courseinfo = $DB->get_records_sql($sql, $groupidparams);
315 foreach ($linkeditems as $convid => $groupid) {
316 if (array_key_exists($groupid, $courseinfo)) {
003cdcce
JD
317 $group = $courseinfo[$groupid];
318 // Subname.
319 $extrafields[$convid]['subname'] = format_string($courseinfo[$groupid]->courseshortname);
320
321 // Imageurl.
322 $extrafields[$convid]['imageurl'] = get_group_picture_url($group, $group->courseid, true)->out(false);
eb5865da
JD
323 }
324 }
325 }
003cdcce 326 return $extrafields;
eb5865da
JD
327 }
328
329
879e2bef
MN
330 /**
331 * Returns the contacts and their conversation to display in the contacts area.
332 *
349f4261
RW
333 * ** WARNING **
334 * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
335 * to retrieve too much information in a single call will cause performance problems.
336 * ** WARNING **
337 *
338 * This function has specifically been altered to break each of the data sets it
339 * requires into separate database calls. This is to avoid the performance problems
340 * observed when attempting to join large data sets (e.g. the message tables and
341 * the user table).
342 *
343 * While it is possible to gather the data in a single query, and it may even be
344 * more efficient with a correctly tuned database, we have opted to trade off some of
345 * the benefits of a single query in order to ensure this function will work on
346 * most databases with default tunings and with large data sets.
347 *
879e2bef 348 * @param int $userid The user id
879e2bef
MN
349 * @param int $limitfrom
350 * @param int $limitnum
eb5865da
JD
351 * @param int $type the type of the conversation, if you wish to filter to a certain type (see api constants).
352 * @param bool $favourites whether to include NO favourites (false) or ONLY favourites (true), or null to ignore this setting.
353 * @return array the array of conversations
354 * @throws \moodle_exception
879e2bef 355 */
b8ff2c44 356 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20, int $type = null,
eb5865da 357 bool $favourites = null) {
349f4261
RW
358 global $DB;
359
eb5865da
JD
360 if (!is_null($type) && !in_array($type, [self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
361 self::MESSAGE_CONVERSATION_TYPE_GROUP])) {
362 throw new \moodle_exception("Invalid value ($type) for type param, please see api constants.");
363 }
364
365 // We need to know which conversations are favourites, so we can either:
366 // 1) Include the 'isfavourite' attribute on conversations (when $favourite = null and we're including all conversations)
367 // 2) Restrict the results to ONLY those conversations which are favourites (when $favourite = true)
368 // 3) Restrict the results to ONLY those conversations which are NOT favourites (when $favourite = false).
369 $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
370 $favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
371 $favouriteconversationids = array_column($favouriteconversations, 'itemid');
372 if ($favourites && empty($favouriteconversationids)) {
373 return []; // If we are aiming to return ONLY favourites, and we have none, there's nothing more to do.
374 }
375
376 // CONVERSATIONS AND MOST RECENT MESSAGE.
377 // Include those conversations with messages first (ordered by most recent message, desc), then add any conversations which
378 // don't have messages, such as newly created group conversations.
379 // Because we're sorting by message 'timecreated', those conversations without messages could be at either the start or the
380 // end of the results (behaviour for sorting of nulls differs between DB vendors), so we use the case to presort these.
381
382 // If we need to return ONLY favourites, or NO favourites, generate the SQL snippet.
b8ff2c44
JD
383 $favouritesql = "";
384 $favouriteparams = [];
eb5865da
JD
385 if (is_bool($favourites)) {
386 if (!empty($favouriteconversationids)) {
387 list ($insql, $inparams) = $DB->get_in_or_equal($favouriteconversationids, SQL_PARAMS_NAMED, 'favouriteids');
388 $favouritesql = $favourites ? " AND mc.id {$insql} " : " AND mc.id NOT {$insql} ";
389 $favouriteparams = $inparams;
b8ff2c44 390 }
b8ff2c44
JD
391 }
392
eb5865da
JD
393 // If we need to restrict type, generate the SQL snippet.
394 $typesql = !is_null($type) ? " AND mc.type = :convtype " : "";
395
396 $sql = "SELECT m.id as messageid, mc.id as id, mc.name as conversationname, mc.type as conversationtype, m.useridfrom,
74fc14e5
JD
397 m.smallmessage, m.fullmessage, m.fullmessageformat, m.fullmessagehtml, m.timecreated, mc.component,
398 mc.itemtype, mc.itemid
eb5865da
JD
399 FROM {message_conversations} mc
400 INNER JOIN {message_conversation_members} mcm
401 ON (mcm.conversationid = mc.id AND mcm.userid = :userid3)
402 LEFT JOIN (
403 SELECT m.conversationid, MAX(m.id) AS messageid
883ce421
MN
404 FROM {messages} m
405 INNER JOIN (
406 SELECT m.conversationid, MAX(m.timecreated) as maxtime
407 FROM {messages} m
408 INNER JOIN {message_conversation_members} mcm
409 ON mcm.conversationid = m.conversationid
410 LEFT JOIN {message_user_actions} mua
411 ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
412 WHERE mua.id is NULL
413 AND mcm.userid = :userid2
414 GROUP BY m.conversationid
415 ) maxmessage
416 ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
417 GROUP BY m.conversationid
418 ) lastmessage
eb5865da
JD
419 ON lastmessage.conversationid = mc.id
420 LEFT JOIN {messages} m
421 ON m.id = lastmessage.messageid
422 WHERE mc.id IS NOT NULL $typesql $favouritesql
423 ORDER BY (CASE WHEN m.timecreated IS NULL THEN 0 ELSE 1 END) DESC, m.timecreated DESC, id DESC";
b8ff2c44
JD
424
425 $params = array_merge($favouriteparams, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
eb5865da
JD
426 'userid2' => $userid, 'userid3' => $userid, 'convtype' => $type]);
427 $conversationset = $DB->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
428
429 $conversations = [];
430 $uniquemembers = [];
431 $members = [];
432 foreach ($conversationset as $conversation) {
433 $conversations[] = $conversation;
434 $members[$conversation->id] = [];
349f4261 435 }
eb5865da 436 $conversationset->close();
349f4261 437
eb5865da
JD
438 // If there are no conversations found, then return early.
439 if (empty($conversations)) {
883ce421
MN
440 return [];
441 }
442
003cdcce
JD
443 // COMPONENT-LINKED CONVERSATION FIELDS.
444 // Conversations linked to components may have extra information, such as:
445 // - subname: Essentially a subtitle for the conversation. So you'd have "name: subname".
446 // - imageurl: A URL to the image for the linked conversation.
eb5865da 447 // For now, this is ONLY course groups.
003cdcce 448 $convextrafields = self::get_linked_conversation_extra_fields($conversations);
eb5865da
JD
449
450 // MEMBERS.
451 // Ideally, we want to get 1 member for each conversation, but this depends on the type and whether there is a recent
452 // message or not.
453 //
454 // For 'individual' type conversations between 2 users, regardless of who sent the last message,
455 // we want the details of the other member in the conversation (i.e. not the current user).
456 //
457 // For 'group' type conversations, we want the details of the member who sent the last message, if there is one.
458 // This can be the current user or another group member, but for groups without messages, this will be empty.
459 //
460 // This also means that if type filtering is specified and only group conversations are returned, we don't need this extra
461 // query to get the 'other' user as we already have that information.
462
463 // Work out which members we have already, and which ones we might need to fetch.
464 // If all the last messages were from another user, then we don't need to fetch anything further.
465 foreach ($conversations as $conversation) {
466 if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
467 if (!is_null($conversation->useridfrom) && $conversation->useridfrom != $userid) {
468 $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
469 $uniquemembers[$conversation->useridfrom] = $conversation->useridfrom;
470 } else {
471 $individualconversations[] = $conversation->id;
472 }
473 } else if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
474 // If we have a recent message, the sender is our member.
475 if (!is_null($conversation->useridfrom)) {
476 $members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
477 $uniquemembers[$conversation->useridfrom] = $conversation->useridfrom;
478 }
479 }
480 }
481 // If we need to fetch any member information for any of the individual conversations.
482 // This is the case if any of the individual conversations have a recent message sent by the current user.
483 if (!empty($individualconversations)) {
484 list ($icidinsql, $icidinparams) = $DB->get_in_or_equal($individualconversations, SQL_PARAMS_NAMED, 'convid');
485 $indmembersql = "SELECT mcm.id, mcm.conversationid, mcm.userid
486 FROM {message_conversation_members} mcm
487 WHERE mcm.conversationid $icidinsql
488 AND mcm.userid != :userid
489 ORDER BY mcm.id";
490 $indmemberparams = array_merge($icidinparams, ['userid' => $userid]);
491 $conversationmembers = $DB->get_records_sql($indmembersql, $indmemberparams);
492
493 foreach ($conversationmembers as $mid => $member) {
494 $members[$member->conversationid][$member->userid] = $member->userid;
495 $uniquemembers[$member->userid] = $member->userid;
496 }
497 }
498 $memberids = array_values($uniquemembers);
499
500 // We could fail early here if we're sure that:
501 // a) we have no otherusers for all the conversations (users may have been deleted)
502 // b) we're sure that all conversations are individual (1:1).
503
504 // We need to pull out the list of users info corresponding to the memberids in the conversations.This
349f4261
RW
505 // needs to be done in a separate query to avoid doing a join on the messages tables and the user
506 // tables because on large sites these tables are massive which results in extremely slow
507 // performance (typically due to join buffer exhaustion).
eb5865da
JD
508 if (!empty($memberids)) {
509 $memberinfo = helper::get_member_info($userid, $memberids);
510
511 // Update the members array with the member information.
512 $deletedmembers = [];
513 foreach ($members as $convid => $memberarr) {
514 foreach ($memberarr as $key => $memberid) {
515 if (array_key_exists($memberid, $memberinfo)) {
516 // If the user is deleted, remember that.
517 if ($memberinfo[$memberid]->isdeleted) {
518 $deletedmembers[$convid][] = $memberid;
519 }
520 $members[$convid][$key] = $memberinfo[$memberid];
521 }
522 }
523 }
883ce421
MN
524 }
525
eb5865da
JD
526 // MEMBER COUNT.
527 $cids = array_column($conversations, 'id');
528 list ($cidinsql, $cidinparams) = $DB->get_in_or_equal($cids, SQL_PARAMS_NAMED, 'convid');
529 $membercountsql = "SELECT conversationid, count(id) AS membercount
530 FROM {message_conversation_members} mcm
531 WHERE mcm.conversationid $cidinsql
532 GROUP BY mcm.conversationid";
533 $membercounts = $DB->get_records_sql($membercountsql, $cidinparams);
534
535 // UNREAD MESSAGE COUNT.
536 // Finally, let's get the unread messages count for this user so that we can add it
883ce421 537 // to the conversation. Remember we need to ignore the messages the user sent.
eb5865da 538 $unreadcountssql = 'SELECT m.conversationid, count(m.id) as unreadcount
883ce421
MN
539 FROM {messages} m
540 INNER JOIN {message_conversations} mc
541 ON mc.id = m.conversationid
542 INNER JOIN {message_conversation_members} mcm
543 ON m.conversationid = mcm.conversationid
544 LEFT JOIN {message_user_actions} mua
545 ON (mua.messageid = m.id AND mua.userid = ? AND
546 (mua.action = ? OR mua.action = ?))
547 WHERE mcm.userid = ?
548 AND m.useridfrom != ?
549 AND mua.id is NULL
eb5865da 550 GROUP BY m.conversationid';
883ce421
MN
551 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
552 $userid, $userid]);
553
eb5865da
JD
554 // Now, create the final return structure.
555 $arrconversations = [];
556 foreach ($conversations as $conversation) {
aa748351
JD
557 // Do not include any individual conversation which:
558 // a) Contains a deleted member or
559 // b) Does not contain a recent message for the user (this happens if the user has deleted all messages).
560 // Group conversations with deleted users or no messages are always returned.
561 if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL
562 && (isset($deletedmembers[$conversation->id]) || empty($conversation->messageid))) {
883ce421
MN
563 continue;
564 }
565
eb5865da
JD
566 $conv = new \stdClass();
567 $conv->id = $conversation->id;
568 $conv->name = $conversation->conversationname;
003cdcce
JD
569 $conv->subname = $convextrafields[$conv->id]['subname'] ?? null;
570 $conv->imageurl = $convextrafields[$conv->id]['imageurl'] ?? null;
eb5865da
JD
571 $conv->type = $conversation->conversationtype;
572 $conv->membercount = $membercounts[$conv->id]->membercount;
573 $conv->isfavourite = in_array($conv->id, $favouriteconversationids);
574 $conv->isread = isset($unreadcounts[$conv->id]) ? false : true;
575 $conv->unreadcount = isset($unreadcounts[$conv->id]) ? $unreadcounts[$conv->id]->unreadcount : null;
576 $conv->members = $members[$conv->id];
577
578 // Add the most recent message information.
579 $conv->messages = [];
580 if ($conversation->smallmessage) {
581 $msg = new \stdClass();
582 $msg->id = $conversation->messageid;
74fc14e5 583 $msg->text = message_format_message_text($conversation);
eb5865da
JD
584 $msg->useridfrom = $conversation->useridfrom;
585 $msg->timecreated = $conversation->timecreated;
586 $conv->messages[] = $msg;
349f4261
RW
587 }
588
eb5865da 589 $arrconversations[] = $conv;
879e2bef 590 }
de55cb1b 591 return $arrconversations;
879e2bef
MN
592 }
593
b8ff2c44
JD
594 /**
595 * Mark a conversation as a favourite for the given user.
596 *
597 * @param int $conversationid the id of the conversation to mark as a favourite.
598 * @param int $userid the id of the user to whom the favourite belongs.
599 * @return favourite the favourite object.
600 * @throws \moodle_exception if the user or conversation don't exist.
601 */
602 public static function set_favourite_conversation(int $conversationid, int $userid) : favourite {
603 if (!self::is_user_in_conversation($userid, $conversationid)) {
604 throw new \moodle_exception("Conversation doesn't exist or user is not a member");
605 }
606 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
607 return $ufservice->create_favourite('core_message', 'message_conversations', $conversationid, \context_system::instance());
608 }
609
610 /**
611 * Unset a conversation as a favourite for the given user.
612 *
613 * @param int $conversationid the id of the conversation to unset as a favourite.
614 * @param int $userid the id to whom the favourite belongs.
615 * @throws \moodle_exception if the favourite does not exist for the user.
616 */
617 public static function unset_favourite_conversation(int $conversationid, int $userid) {
618 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
619 $ufservice->delete_favourite('core_message', 'message_conversations', $conversationid, \context_system::instance());
620 }
621
879e2bef
MN
622 /**
623 * Returns the contacts to display in the contacts area.
624 *
625 * @param int $userid The user id
626 * @param int $limitfrom
627 * @param int $limitnum
de55cb1b 628 * @return array
879e2bef
MN
629 */
630 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
631 global $DB;
632
f219eac7
MN
633 $contactids = [];
634 $sql = "SELECT mc.*
879e2bef 635 FROM {message_contacts} mc
f219eac7
MN
636 WHERE mc.userid = ? OR mc.contactid = ?
637 ORDER BY timecreated DESC";
638 if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
879e2bef 639 foreach ($contacts as $contact) {
f219eac7
MN
640 if ($userid == $contact->userid) {
641 $contactids[] = $contact->contactid;
642 } else {
643 $contactids[] = $contact->userid;
644 }
645 }
646 }
647
648 if (!empty($contactids)) {
649 list($insql, $inparams) = $DB->get_in_or_equal($contactids);
650
651 $sql = "SELECT u.*, mub.id as isblocked
652 FROM {user} u
653 LEFT JOIN {message_users_blocked} mub
654 ON u.id = mub.blockeduserid
655 WHERE u.id $insql";
656 if ($contacts = $DB->get_records_sql($sql, $inparams)) {
657 $arrcontacts = [];
658 foreach ($contacts as $contact) {
659 $contact->blocked = $contact->isblocked ? 1 : 0;
660 $arrcontacts[] = helper::create_contact($contact);
661 }
662
663 return $arrcontacts;
879e2bef
MN
664 }
665 }
666
f219eac7 667 return [];
879e2bef
MN
668 }
669
883ce421
MN
670 /**
671 * Returns the an array of the users the given user is in a conversation
672 * with who are a contact and the number of unread messages.
673 *
674 * @param int $userid The user id
675 * @param int $limitfrom
676 * @param int $limitnum
677 * @return array
678 */
679 public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
680 global $DB;
681
682 $userfields = \user_picture::fields('u', array('lastaccess'));
683 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
684 FROM {message_contacts} mc
685 INNER JOIN {user} u
f219eac7 686 ON (u.id = mc.contactid OR u.id = mc.userid)
883ce421 687 LEFT JOIN {messages} m
f219eac7 688 ON ((m.useridfrom = mc.contactid OR m.useridfrom = mc.userid) AND m.useridfrom != ?)
883ce421
MN
689 LEFT JOIN {message_conversation_members} mcm
690 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
691 LEFT JOIN {message_user_actions} mua
692 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
f219eac7
MN
693 LEFT JOIN {message_users_blocked} mub
694 ON (mub.userid = ? AND mub.blockeduserid = u.id)
883ce421 695 WHERE mua.id is NULL
f219eac7
MN
696 AND mub.id is NULL
697 AND (mc.userid = ? OR mc.contactid = ?)
698 AND u.id != ?
883ce421
MN
699 AND u.deleted = 0
700 GROUP BY $userfields";
701
f219eac7
MN
702 return $DB->get_records_sql($unreadcountssql, [$userid, $userid, $userid, self::MESSAGE_ACTION_READ,
703 $userid, $userid, $userid, $userid], $limitfrom, $limitnum);
883ce421
MN
704 }
705
706 /**
707 * Returns the an array of the users the given user is in a conversation
708 * with who are not a contact and the number of unread messages.
709 *
710 * @param int $userid The user id
711 * @param int $limitfrom
712 * @param int $limitnum
713 * @return array
714 */
715 public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
716 global $DB;
717
718 $userfields = \user_picture::fields('u', array('lastaccess'));
719 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
720 FROM {user} u
721 INNER JOIN {messages} m
722 ON m.useridfrom = u.id
723 INNER JOIN {message_conversation_members} mcm
724 ON mcm.conversationid = m.conversationid
725 LEFT JOIN {message_user_actions} mua
726 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
727 LEFT JOIN {message_contacts} mc
728 ON (mc.userid = ? AND mc.contactid = u.id)
f219eac7
MN
729 LEFT JOIN {message_users_blocked} mub
730 ON (mub.userid = ? AND mub.blockeduserid = u.id)
883ce421
MN
731 WHERE mcm.userid = ?
732 AND mcm.userid != m.useridfrom
733 AND mua.id is NULL
f219eac7 734 AND mub.id is NULL
883ce421
MN
735 AND mc.id is NULL
736 AND u.deleted = 0
737 GROUP BY $userfields";
738
f219eac7 739 return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
883ce421
MN
740 $limitfrom, $limitnum);
741 }
742
879e2bef
MN
743 /**
744 * Returns the messages to display in the message area.
745 *
d1e8e69d 746 * @deprecated since 3.6
879e2bef
MN
747 * @param int $userid the current user
748 * @param int $otheruserid the other user
749 * @param int $limitfrom
750 * @param int $limitnum
8ec78c48 751 * @param string $sort
ffd7798c
MN
752 * @param int $timefrom the time from the message being sent
753 * @param int $timeto the time up until the message being sent
de55cb1b 754 * @return array
879e2bef 755 */
fb1469d8 756 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
d1e8e69d
MN
757 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
758 debugging('\core_message\api::get_messages() is deprecated, please use ' .
759 '\core_message\api::get_conversation_messages() instead.', DEBUG_DEVELOPER);
fb1469d8 760
ffd7798c 761 if (!empty($timefrom)) {
fb04293b
SA
762 // Get the conversation between userid and otheruserid.
763 $userids = [$userid, $otheruserid];
764 if (!$conversationid = self::get_conversation_between_users($userids)) {
765 // This method was always used for individual conversations.
766 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
767 $conversationid = $conversation->id;
768 }
769
fb1469d8 770 // Check the cache to see if we even need to do a DB query.
4699b8bc
AN
771 $cache = \cache::make('core', 'message_time_last_message_between_users');
772 $key = helper::get_last_message_time_created_cache_key($conversationid);
773 $lastcreated = $cache->get($key);
fb1469d8
RW
774
775 // The last known message time is earlier than the one being requested so we can
776 // just return an empty result set rather than having to query the DB.
ffd7798c 777 if ($lastcreated && $lastcreated < $timefrom) {
fb1469d8
RW
778 return [];
779 }
780 }
781
879e2bef 782 $arrmessages = array();
fb1469d8 783 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
ffd7798c 784 $sort, $timefrom, $timeto)) {
de55cb1b 785 $arrmessages = helper::create_messages($userid, $messages);
879e2bef
MN
786 }
787
de55cb1b 788 return $arrmessages;
879e2bef 789 }
c060cd49 790
fb04293b
SA
791 /**
792 * Returns the messages for the defined conversation.
793 *
794 * @param int $userid The current user.
795 * @param int $convid The conversation where the messages belong. Could be an object or just the id.
796 * @param int $limitfrom Return a subset of records, starting at this point (optional).
797 * @param int $limitnum Return a subset comprising this many records in total (optional, required if $limitfrom is set).
798 * @param string $sort The column name to order by including optionally direction.
799 * @param int $timefrom The time from the message being sent.
800 * @param int $timeto The time up until the message being sent.
801 * @return array of messages
802 */
803 public static function get_conversation_messages(int $userid, int $convid, int $limitfrom = 0, int $limitnum = 0,
804 string $sort = 'timecreated ASC', int $timefrom = 0, int $timeto = 0) : array {
805
806 if (!empty($timefrom)) {
807 // Check the cache to see if we even need to do a DB query.
74138e92 808 $cache = \cache::make('core', 'message_time_last_message_between_users');
4699b8bc
AN
809 $key = helper::get_last_message_time_created_cache_key($convid);
810 $lastcreated = $cache->get($key);
fb04293b
SA
811
812 // The last known message time is earlier than the one being requested so we can
813 // just return an empty result set rather than having to query the DB.
814 if ($lastcreated && $lastcreated < $timefrom) {
815 return [];
816 }
817 }
818
819 $arrmessages = array();
820 if ($messages = helper::get_conversation_messages($userid, $convid, 0, $limitfrom, $limitnum, $sort, $timefrom, $timeto)) {
821 $arrmessages = helper::format_conversation_messages($userid, $convid, $messages);
822 }
823
824 return $arrmessages;
825 }
826
c060cd49
MN
827 /**
828 * Returns the most recent message between two users.
829 *
d1e8e69d 830 * @deprecated since 3.6
c060cd49
MN
831 * @param int $userid the current user
832 * @param int $otheruserid the other user
de55cb1b 833 * @return \stdClass|null
c060cd49
MN
834 */
835 public static function get_most_recent_message($userid, $otheruserid) {
d1e8e69d
MN
836 debugging('\core_message\api::get_most_recent_message() is deprecated, please use ' .
837 '\core_message\api::get_most_recent_conversation_message() instead.', DEBUG_DEVELOPER);
838
c060cd49 839 // We want two messages here so we get an accurate 'blocktime' value.
de55cb1b 840 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
841 // Swap the order so we now have them in historical order.
842 $messages = array_reverse($messages);
de55cb1b 843 $arrmessages = helper::create_messages($userid, $messages);
c060cd49
MN
844 return array_pop($arrmessages);
845 }
846
847 return null;
848 }
c6e97f54 849
fb04293b
SA
850 /**
851 * Returns the most recent message in a conversation.
852 *
853 * @param int $convid The conversation identifier.
854 * @param int $currentuserid The current user identifier.
855 * @return \stdClass|null The most recent message.
856 */
857 public static function get_most_recent_conversation_message(int $convid, int $currentuserid = 0) {
858 global $USER;
859
860 if (empty($currentuserid)) {
861 $currentuserid = $USER->id;
862 }
863
864 if ($messages = helper::get_conversation_messages($currentuserid, $convid, 0, 0, 1, 'timecreated DESC')) {
865 $convmessages = helper::format_conversation_messages($currentuserid, $convid, $messages);
866 return array_pop($convmessages['messages']);
867 }
868
869 return null;
870 }
871
c6e97f54
MN
872 /**
873 * Returns the profile information for a contact for a user.
874 *
875 * @param int $userid The user id
876 * @param int $otheruserid The id of the user whose profile we want to view.
de55cb1b 877 * @return \stdClass
c6e97f54
MN
878 */
879 public static function get_profile($userid, $otheruserid) {
f219eac7 880 global $CFG, $PAGE;
c6e97f54
MN
881
882 require_once($CFG->dirroot . '/user/lib.php');
883
f4c39cb9
MN
884 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
885
886 // Create the data we are going to pass to the renderable.
887 $data = new \stdClass();
888 $data->userid = $otheruserid;
889 $data->fullname = fullname($user);
890 $data->city = '';
891 $data->country = '';
892 $data->email = '';
cb805753 893 $data->isonline = null;
f4c39cb9
MN
894 // Get the user picture data - messaging has always shown these to the user.
895 $userpicture = new \user_picture($user);
896 $userpicture->size = 1; // Size f1.
897 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
898 $userpicture->size = 0; // Size f2.
899 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
900
901 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
902 if ($userfields) {
903 if (isset($userfields['city'])) {
904 $data->city = $userfields['city'];
905 }
906 if (isset($userfields['country'])) {
907 $data->country = $userfields['country'];
bf58081d 908 }
f4c39cb9
MN
909 if (isset($userfields['email'])) {
910 $data->email = $userfields['email'];
c6e97f54 911 }
f4c39cb9
MN
912 if (isset($userfields['lastaccess'])) {
913 $data->isonline = helper::is_online($userfields['lastaccess']);
914 }
915 }
c6e97f54 916
f219eac7
MN
917 $data->isblocked = self::is_blocked($userid, $otheruserid);
918 $data->iscontact = self::is_contact($userid, $otheruserid);
f4c39cb9
MN
919
920 return $data;
c6e97f54 921 }
dec0cd99
MN
922
923 /**
924 * Checks if a user can delete messages they have either received or sent.
925 *
926 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
927 * but will still seem as if it was by the user)
15663b0b 928 * @param int $conversationid The id of the conversation
1f64514d 929 * @return bool Returns true if a user can delete the conversation, false otherwise.
dec0cd99 930 */
15663b0b 931 public static function can_delete_conversation(int $userid, int $conversationid = null) : bool {
dec0cd99
MN
932 global $USER;
933
15663b0b
MN
934 if (is_null($conversationid)) {
935 debugging('\core_message\api::can_delete_conversation() now expects a \'conversationid\' to be passed.',
936 DEBUG_DEVELOPER);
937 return false;
938 }
939
dec0cd99
MN
940 $systemcontext = \context_system::instance();
941
15663b0b
MN
942 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
943 return true;
944 }
945
946 if (!self::is_user_in_conversation($userid, $conversationid)) {
947 return false;
948 }
949
950 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
951 $USER->id == $userid) {
dec0cd99
MN
952 return true;
953 }
954
955 return false;
956 }
957
958 /**
959 * Deletes a conversation.
960 *
961 * This function does not verify any permissions.
962 *
263ad984 963 * @deprecated since 3.6
dec0cd99
MN
964 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
965 * but will still seem as if it was by the user)
966 * @param int $otheruserid The id of the other user in the conversation
967 * @return bool
968 */
969 public static function delete_conversation($userid, $otheruserid) {
263ad984
MN
970 debugging('\core_message\api::delete_conversation() is deprecated, please use ' .
971 '\core_message\api::delete_conversation_by_id() instead.', DEBUG_DEVELOPER);
dec0cd99 972
b2cd17e6 973 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
dec0cd99 974
883ce421
MN
975 // If there is no conversation, there is nothing to do.
976 if (!$conversationid) {
977 return true;
978 }
979
263ad984
MN
980 self::delete_conversation_by_id($userid, $conversationid);
981
982 return true;
983 }
984
985 /**
986 * Deletes a conversation for a specified user.
987 *
988 * This function does not verify any permissions.
989 *
990 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
991 * but will still seem as if it was by the user)
992 * @param int $conversationid The id of the other user in the conversation
993 */
994 public static function delete_conversation_by_id(int $userid, int $conversationid) {
995 global $DB, $USER;
996
883ce421
MN
997 // Get all messages belonging to this conversation that have not already been deleted by this user.
998 $sql = "SELECT m.*
999 FROM {messages} m
1000 INNER JOIN {message_conversations} mc
1001 ON m.conversationid = mc.id
1002 LEFT JOIN {message_user_actions} mua
1003 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1004 WHERE mua.id is NULL
1005 AND mc.id = ?
1006 ORDER BY m.timecreated ASC";
1007 $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
1008
1009 // Ok, mark these as deleted.
1010 foreach ($messages as $message) {
1011 $mua = new \stdClass();
1012 $mua->userid = $userid;
1013 $mua->messageid = $message->id;
1014 $mua->action = self::MESSAGE_ACTION_DELETED;
1015 $mua->timecreated = time();
1016 $mua->id = $DB->insert_record('message_user_actions', $mua);
1017
14de10c4
MN
1018 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1019 $message->id, $mua->id)->trigger();
dec0cd99 1020 }
dec0cd99 1021 }
79f6c36c
MN
1022
1023 /**
1024 * Returns the count of unread conversations (collection of messages from a single user) for
1025 * the given user.
1026 *
1027 * @param \stdClass $user the user who's conversations should be counted
1028 * @return int the count of the user's unread conversations
1029 */
1030 public static function count_unread_conversations($user = null) {
1031 global $USER, $DB;
1032
1033 if (empty($user)) {
1034 $user = $USER;
1035 }
1036
883ce421
MN
1037 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
1038 FROM {messages} m
1039 INNER JOIN {message_conversations} mc
1040 ON m.conversationid = mc.id
1041 INNER JOIN {message_conversation_members} mcm
1042 ON mc.id = mcm.conversationid
1043 LEFT JOIN {message_user_actions} mua
1044 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1045 WHERE mcm.userid = ?
1046 AND mcm.userid != m.useridfrom
1047 AND mua.id is NULL";
1048
1049 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
79f6c36c
MN
1050 }
1051
abf7a261
MN
1052 /**
1053 * Checks if a user can mark all messages as read.
1054 *
1055 * @param int $userid The user id of who we want to mark the messages for
1056 * @param int $conversationid The id of the conversation
1057 * @return bool true if user is permitted, false otherwise
1058 * @since 3.6
1059 */
1060 public static function can_mark_all_messages_as_read(int $userid, int $conversationid) : bool {
1061 global $USER;
1062
1063 $systemcontext = \context_system::instance();
1064
1065 if (has_capability('moodle/site:readallmessages', $systemcontext)) {
1066 return true;
1067 }
1068
1069 if (!self::is_user_in_conversation($userid, $conversationid)) {
1070 return false;
1071 }
1072
1073 if ($USER->id == $userid) {
1074 return true;
1075 }
1076
1077 return false;
1078 }
1079
79f6c36c 1080 /**
74ad60bf 1081 * Marks all messages being sent to a user in a particular conversation.
79f6c36c 1082 *
74ad60bf 1083 * If $conversationdid is null then it marks all messages as read sent to $userid.
79f6c36c 1084 *
74ad60bf
MN
1085 * @param int $userid
1086 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
79f6c36c 1087 */
74ad60bf 1088 public static function mark_all_messages_as_read($userid, $conversationid = null) {
79f6c36c
MN
1089 global $DB;
1090
883ce421
MN
1091 $messagesql = "SELECT m.*
1092 FROM {messages} m
1093 INNER JOIN {message_conversations} mc
1094 ON mc.id = m.conversationid
1095 INNER JOIN {message_conversation_members} mcm
1096 ON mcm.conversationid = mc.id
5aac33c7
MN
1097 LEFT JOIN {message_user_actions} mua
1098 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1099 WHERE mua.id is NULL
1100 AND mcm.userid = ?
74ad60bf 1101 AND m.useridfrom != ?";
5aac33c7
MN
1102 $messageparams = [];
1103 $messageparams[] = $userid;
1104 $messageparams[] = self::MESSAGE_ACTION_READ;
74ad60bf
MN
1105 $messageparams[] = $userid;
1106 $messageparams[] = $userid;
1107 if (!is_null($conversationid)) {
1108 $messagesql .= " AND mc.id = ?";
1109 $messageparams[] = $conversationid;
79f6c36c
MN
1110 }
1111
74ad60bf
MN
1112 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
1113 foreach ($messages as $message) {
1114 self::mark_message_as_read($userid, $message);
1115 }
1116 $messages->close();
1117 }
1118
1119 /**
1120 * Marks all notifications being sent from one user to another user as read.
1121 *
1122 * If the from user is null then it marks all notifications as read sent to the to user.
1123 *
1124 * @param int $touserid the id of the message recipient
1125 * @param int|null $fromuserid the id of the message sender, null if all messages
1126 * @return void
1127 */
1128 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
1129 global $DB;
1130
883ce421
MN
1131 $notificationsql = "SELECT n.*
1132 FROM {notifications} n
74ad60bf
MN
1133 WHERE useridto = ?
1134 AND timeread is NULL";
883ce421 1135 $notificationsparams = [$touserid];
79f6c36c 1136 if (!empty($fromuserid)) {
883ce421
MN
1137 $notificationsql .= " AND useridfrom = ?";
1138 $notificationsparams[] = $fromuserid;
79f6c36c
MN
1139 }
1140
74ad60bf
MN
1141 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
1142 foreach ($notifications as $notification) {
1143 self::mark_notification_as_read($notification);
79f6c36c 1144 }
74ad60bf
MN
1145 $notifications->close();
1146 }
79f6c36c 1147
74ad60bf
MN
1148 /**
1149 * Marks ALL messages being sent from $fromuserid to $touserid as read.
1150 *
1151 * Can be filtered by type.
1152 *
1153 * @deprecated since 3.5
1154 * @param int $touserid the id of the message recipient
1155 * @param int $fromuserid the id of the message sender
1156 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
1157 * @return void
1158 */
1159 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
1160 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
1161 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
1162 DEBUG_DEVELOPER);
1163
1164 $type = strtolower($type);
1165
1166 $conversationid = null;
1167 $ignoremessages = false;
1168 if (!empty($fromuserid)) {
99248f61 1169 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
74ad60bf
MN
1170 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
1171 $ignoremessages = true;
1172 }
79f6c36c
MN
1173 }
1174
74ad60bf
MN
1175 if (!empty($type)) {
1176 if ($type == MESSAGE_TYPE_NOTIFICATION) {
99248f61 1177 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf
MN
1178 } else if ($type == MESSAGE_TYPE_MESSAGE) {
1179 if (!$ignoremessages) {
99248f61 1180 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf
MN
1181 }
1182 }
1183 } else { // We want both.
99248f61 1184 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf 1185 if (!$ignoremessages) {
99248f61 1186 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf 1187 }
883ce421 1188 }
79f6c36c
MN
1189 }
1190
79f6c36c
MN
1191 /**
1192 * Returns message preferences.
1193 *
1194 * @param array $processors
1195 * @param array $providers
1196 * @param \stdClass $user
1197 * @return \stdClass
1198 * @since 3.2
1199 */
1200 public static function get_all_message_preferences($processors, $providers, $user) {
1201 $preferences = helper::get_providers_preferences($providers, $user->id);
1202 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
1203
1204 // For every processors put its options on the form (need to get function from processor's lib.php).
1205 foreach ($processors as $processor) {
1206 $processor->object->load_data($preferences, $user->id);
1207 }
1208
1209 // Load general messaging preferences.
f7dfa9ba 1210 $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
79f6c36c
MN
1211 $preferences->mailformat = $user->mailformat;
1212 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
1213
1214 return $preferences;
1215 }
5b0769db
MN
1216
1217 /**
1218 * Count the number of users blocked by a user.
1219 *
1220 * @param \stdClass $user The user object
1221 * @return int the number of blocked users
1222 */
1223 public static function count_blocked_users($user = null) {
1224 global $USER, $DB;
1225
1226 if (empty($user)) {
1227 $user = $USER;
1228 }
1229
f219eac7
MN
1230 $sql = "SELECT count(mub.id)
1231 FROM {message_users_blocked} mub
1232 WHERE mub.userid = :userid";
5b0769db
MN
1233 return $DB->count_records_sql($sql, array('userid' => $user->id));
1234 }
1235
1236 /**
1237 * Determines if a user is permitted to send another user a private message.
1238 * If no sender is provided then it defaults to the logged in user.
1239 *
1240 * @param \stdClass $recipient The user object.
1241 * @param \stdClass|null $sender The user object.
1242 * @return bool true if user is permitted, false otherwise.
1243 */
1244 public static function can_post_message($recipient, $sender = null) {
1245 global $USER;
1246
1247 if (is_null($sender)) {
1248 // The message is from the logged in user, unless otherwise specified.
1249 $sender = $USER;
1250 }
1251
7983fb83
SA
1252 $systemcontext = \context_system::instance();
1253 if (!has_capability('moodle/site:sendmessage', $systemcontext, $sender)) {
5b0769db
MN
1254 return false;
1255 }
1256
7983fb83 1257 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender->id)) {
c886e2c9
MN
1258 return true;
1259 }
1260
7983fb83
SA
1261 // Check if the recipient can be messaged by the sender.
1262 return (self::can_contact_user($recipient, $sender));
5b0769db
MN
1263 }
1264
f7dfa9ba
SA
1265 /**
1266 * Get the messaging preference for a user.
1267 * If the user has not any messaging privacy preference:
1268 * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
1269 * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
1270 *
1271 * @param int $userid The user identifier.
1272 * @return int The default messaging preference.
1273 */
1274 public static function get_user_privacy_messaging_preference(int $userid) : int {
1275 global $CFG;
1276
1277 // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
1278 // otherwise, the default value will be "My contacts and anyone in my courses".
1279 if (empty($CFG->messagingallusers)) {
1280 $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
1281 } else {
1282 $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
1283 }
1284 $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $userid);
1285
1286 // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
1287 // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1288 if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
1289 $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
1290 }
1291
1292 return $privacypreference;
1293 }
1294
5b0769db
MN
1295 /**
1296 * Checks if the recipient is allowing messages from users that aren't a
1297 * contact. If not then it checks to make sure the sender is in the
1298 * recipient's contacts.
1299 *
e5eba802 1300 * @deprecated since 3.6
5b0769db
MN
1301 * @param \stdClass $recipient The user object.
1302 * @param \stdClass|null $sender The user object.
1303 * @return bool true if $sender is blocked, false otherwise.
1304 */
1305 public static function is_user_non_contact_blocked($recipient, $sender = null) {
e5eba802
SA
1306 debugging('\core_message\api::is_user_non_contact_blocked() is deprecated', DEBUG_DEVELOPER);
1307
f7dfa9ba 1308 global $USER, $CFG;
5b0769db
MN
1309
1310 if (is_null($sender)) {
1311 // The message is from the logged in user, unless otherwise specified.
1312 $sender = $USER;
1313 }
1314
f7dfa9ba
SA
1315 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1316 switch ($privacypreference) {
1317 case self::MESSAGE_PRIVACY_SITE:
1318 if (!empty($CFG->messagingallusers)) {
1319 // Users can be messaged without being contacts or members of the same course.
1320 break;
1321 }
1322 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1323 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1324 case self::MESSAGE_PRIVACY_COURSEMEMBER:
1325 // Confirm the sender and the recipient are both members of the same course.
1326 if (enrol_sharing_course($recipient, $sender)) {
1327 // All good, the recipient and the sender are members of the same course.
1328 return false;
1329 }
1330 case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1331 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1332 return !self::is_contact($sender->id, $recipient->id);
5b0769db
MN
1333 }
1334
1335 return false;
1336 }
1337
1338 /**
1339 * Checks if the recipient has specifically blocked the sending user.
1340 *
1341 * Note: This function will always return false if the sender has the
1342 * readallmessages capability at the system context level.
1343 *
c886e2c9 1344 * @deprecated since 3.6
26dca05d
JP
1345 * @param int $recipientid User ID of the recipient.
1346 * @param int $senderid User ID of the sender.
5b0769db
MN
1347 * @return bool true if $sender is blocked, false otherwise.
1348 */
26dca05d 1349 public static function is_user_blocked($recipientid, $senderid = null) {
c886e2c9
MN
1350 debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1351 DEBUG_DEVELOPER);
1352
1353 global $USER;
5b0769db 1354
26dca05d 1355 if (is_null($senderid)) {
5b0769db 1356 // The message is from the logged in user, unless otherwise specified.
26dca05d 1357 $senderid = $USER->id;
5b0769db
MN
1358 }
1359
1360 $systemcontext = \context_system::instance();
26dca05d 1361 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
5b0769db
MN
1362 return false;
1363 }
1364
f219eac7 1365 if (self::is_blocked($recipientid, $senderid)) {
26dca05d 1366 return true;
5b0769db
MN
1367 }
1368
1369 return false;
1370 }
20ab51fd
AA
1371
1372 /**
1373 * Get specified message processor, validate corresponding plugin existence and
1374 * system configuration.
1375 *
1376 * @param string $name Name of the processor.
1377 * @param bool $ready only return ready-to-use processors.
1378 * @return mixed $processor if processor present else empty array.
1379 * @since Moodle 3.2
1380 */
1381 public static function get_message_processor($name, $ready = false) {
1382 global $DB, $CFG;
1383
1384 $processor = $DB->get_record('message_processors', array('name' => $name));
1385 if (empty($processor)) {
1386 // Processor not found, return.
1387 return array();
1388 }
1389
1390 $processor = self::get_processed_processor_object($processor);
1391 if ($ready) {
1392 if ($processor->enabled && $processor->configured) {
1393 return $processor;
1394 } else {
1395 return array();
1396 }
1397 } else {
1398 return $processor;
1399 }
1400 }
1401
1402 /**
1403 * Returns weather a given processor is enabled or not.
1404 * Note:- This doesn't check if the processor is configured or not.
1405 *
1406 * @param string $name Name of the processor
1407 * @return bool
1408 */
1409 public static function is_processor_enabled($name) {
1410
1411 $cache = \cache::make('core', 'message_processors_enabled');
1412 $status = $cache->get($name);
1413
1414 if ($status === false) {
1415 $processor = self::get_message_processor($name);
1416 if (!empty($processor)) {
1417 $cache->set($name, $processor->enabled);
1418 return $processor->enabled;
1419 } else {
1420 return false;
1421 }
1422 }
1423
1424 return $status;
1425 }
1426
1427 /**
1428 * Set status of a processor.
1429 *
1430 * @param \stdClass $processor processor record.
1431 * @param 0|1 $enabled 0 or 1 to set the processor status.
1432 * @return bool
1433 * @since Moodle 3.2
1434 */
1435 public static function update_processor_status($processor, $enabled) {
1436 global $DB;
1437 $cache = \cache::make('core', 'message_processors_enabled');
1438 $cache->delete($processor->name);
1439 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1440 }
1441
1442 /**
1443 * Given a processor object, loads information about it's settings and configurations.
1444 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1445 * or @see \get_message_processors()
1446 *
1447 * @param \stdClass $processor processor object
1448 * @return \stdClass processed processor object
1449 * @since Moodle 3.2
1450 */
1451 public static function get_processed_processor_object(\stdClass $processor) {
1452 global $CFG;
1453
1454 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1455 if (is_readable($processorfile)) {
1456 include_once($processorfile);
1457 $processclass = 'message_output_' . $processor->name;
1458 if (class_exists($processclass)) {
1459 $pclass = new $processclass();
1460 $processor->object = $pclass;
1461 $processor->configured = 0;
1462 if ($pclass->is_system_configured()) {
1463 $processor->configured = 1;
1464 }
1465 $processor->hassettings = 0;
1466 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1467 $processor->hassettings = 1;
1468 }
1469 $processor->available = 1;
1470 } else {
1471 print_error('errorcallingprocessor', 'message');
1472 }
1473 } else {
1474 $processor->available = 0;
1475 }
1476 return $processor;
1477 }
883ce421
MN
1478
1479 /**
1480 * Retrieve users blocked by $user1
1481 *
1482 * @param int $userid The user id of the user whos blocked users we are returning
1483 * @return array the users blocked
1484 */
1485 public static function get_blocked_users($userid) {
1486 global $DB;
1487
1488 $userfields = \user_picture::fields('u', array('lastaccess'));
1489 $blockeduserssql = "SELECT $userfields
f219eac7 1490 FROM {message_users_blocked} mub
883ce421 1491 INNER JOIN {user} u
f219eac7 1492 ON u.id = mub.blockeduserid
883ce421 1493 WHERE u.deleted = 0
f219eac7 1494 AND mub.userid = ?
883ce421
MN
1495 GROUP BY $userfields
1496 ORDER BY u.firstname ASC";
1497 return $DB->get_records_sql($blockeduserssql, [$userid]);
1498 }
1499
1500 /**
1501 * Mark a single message as read.
1502 *
1503 * @param int $userid The user id who marked the message as read
548936a6 1504 * @param \stdClass $message The message
883ce421
MN
1505 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1506 */
548936a6 1507 public static function mark_message_as_read($userid, $message, $timeread = null) {
883ce421
MN
1508 global $DB;
1509
1510 if (is_null($timeread)) {
1511 $timeread = time();
1512 }
1513
5aac33c7
MN
1514 $mua = new \stdClass();
1515 $mua->userid = $userid;
1516 $mua->messageid = $message->id;
1517 $mua->action = self::MESSAGE_ACTION_READ;
1518 $mua->timecreated = $timeread;
1519 $mua->id = $DB->insert_record('message_user_actions', $mua);
1520
1521 // Get the context for the user who received the message.
1522 $context = \context_user::instance($userid, IGNORE_MISSING);
1523 // If the user no longer exists the context value will be false, in this case use the system context.
1524 if ($context === false) {
1525 $context = \context_system::instance();
883ce421 1526 }
5aac33c7
MN
1527
1528 // Trigger event for reading a message.
1529 $event = \core\event\message_viewed::create(array(
1530 'objectid' => $mua->id,
1531 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1532 'context' => $context,
1533 'relateduserid' => $message->useridfrom,
1534 'other' => array(
1535 'messageid' => $message->id
1536 )
1537 ));
1538 $event->trigger();
883ce421
MN
1539 }
1540
1541 /**
1542 * Mark a single notification as read.
1543 *
548936a6 1544 * @param \stdClass $notification The notification
883ce421
MN
1545 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1546 */
548936a6 1547 public static function mark_notification_as_read($notification, $timeread = null) {
883ce421
MN
1548 global $DB;
1549
1550 if (is_null($timeread)) {
1551 $timeread = time();
1552 }
1553
883ce421
MN
1554 if (is_null($notification->timeread)) {
1555 $updatenotification = new \stdClass();
1556 $updatenotification->id = $notification->id;
1557 $updatenotification->timeread = $timeread;
1558
1559 $DB->update_record('notifications', $updatenotification);
376a79c2
MN
1560
1561 // Trigger event for reading a notification.
1562 \core\event\notification_viewed::create_from_ids(
1563 $notification->useridfrom,
1564 $notification->useridto,
1565 $notification->id
1566 )->trigger();
883ce421
MN
1567 }
1568 }
1569
1570 /**
1571 * Checks if a user can delete a message.
1572 *
1573 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1574 * but will still seem as if it was by the user)
1575 * @param int $messageid The message id
1576 * @return bool Returns true if a user can delete the message, false otherwise.
1577 */
1578 public static function can_delete_message($userid, $messageid) {
1579 global $DB, $USER;
1580
08cb8a34
MN
1581 $systemcontext = \context_system::instance();
1582
1583 $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
1584
1585 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1586 return true;
883ce421
MN
1587 }
1588
08cb8a34
MN
1589 if (!self::is_user_in_conversation($userid, $conversationid)) {
1590 return false;
1591 }
883ce421 1592
08cb8a34
MN
1593 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1594 $USER->id == $userid) {
883ce421
MN
1595 return true;
1596 }
1597
1598 return false;
1599 }
1600
1601 /**
1602 * Deletes a message.
1603 *
1604 * This function does not verify any permissions.
1605 *
1606 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1607 * but will still seem as if it was by the user)
1608 * @param int $messageid The message id
1609 * @return bool
1610 */
1611 public static function delete_message($userid, $messageid) {
14de10c4 1612 global $DB, $USER;
883ce421 1613
14de10c4
MN
1614 if (!$DB->record_exists('messages', ['id' => $messageid])) {
1615 return false;
1616 }
883ce421
MN
1617
1618 // Check if the user has already deleted this message.
1619 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1620 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1621 $mua = new \stdClass();
1622 $mua->userid = $userid;
1623 $mua->messageid = $messageid;
1624 $mua->action = self::MESSAGE_ACTION_DELETED;
1625 $mua->timecreated = time();
1626 $mua->id = $DB->insert_record('message_user_actions', $mua);
1627
1628 // Trigger event for deleting a message.
14de10c4
MN
1629 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1630 $messageid, $mua->id)->trigger();
883ce421
MN
1631
1632 return true;
1633 }
1634
1635 return false;
1636 }
1637
1638 /**
1639 * Returns the conversation between two users.
1640 *
b2cd17e6 1641 * @param array $userids
883ce421
MN
1642 * @return int|bool The id of the conversation, false if not found
1643 */
b2cd17e6 1644 public static function get_conversation_between_users(array $userids) {
883ce421
MN
1645 global $DB;
1646
b2cd17e6 1647 $hash = helper::get_conversation_hash($userids);
883ce421 1648
f2ac0a3e
MN
1649 $params = [
1650 'type' => self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1651 'convhash' => $hash
1652 ];
1653 if ($conversation = $DB->get_record('message_conversations', $params)) {
883ce421
MN
1654 return $conversation->id;
1655 }
1656
1657 return false;
1658 }
1659
1660 /**
1661 * Creates a conversation between two users.
1662 *
a66ae849 1663 * @deprecated since 3.6
b2cd17e6 1664 * @param array $userids
883ce421
MN
1665 * @return int The id of the conversation
1666 */
b2cd17e6 1667 public static function create_conversation_between_users(array $userids) {
a66ae849
MN
1668 debugging('\core_message\api::create_conversation_between_users is deprecated, please use ' .
1669 '\core_message\api::create_conversation instead.', DEBUG_DEVELOPER);
1670
f2ac0a3e
MN
1671 // This method was always used for individual conversations.
1672 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
1673
1674 return $conversation->id;
1675 }
1676
1677 /**
1678 * Creates a conversation with selected users and messages.
1679 *
1680 * @param int $type The type of conversation
1681 * @param int[] $userids The array of users to add to the conversation
76540bec
MN
1682 * @param string|null $name The name of the conversation
1683 * @param int $enabled Determines if the conversation is created enabled or disabled
1684 * @param string|null $component Defines the Moodle component which the conversation belongs to, if any
1685 * @param string|null $itemtype Defines the type of the component
1686 * @param int|null $itemid The id of the component
1687 * @param int|null $contextid The id of the context
f2ac0a3e
MN
1688 * @return \stdClass
1689 */
76540bec
MN
1690 public static function create_conversation(int $type, array $userids, string $name = null,
1691 int $enabled = self::MESSAGE_CONVERSATION_ENABLED, string $component = null,
1692 string $itemtype = null, int $itemid = null, int $contextid = null) {
1693
883ce421
MN
1694 global $DB;
1695
f2ac0a3e
MN
1696 // Sanity check.
1697 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1698 if (count($userids) > 2) {
1699 throw new \moodle_exception('An individual conversation can not have more than two users.');
1700 }
1701 }
1702
883ce421 1703 $conversation = new \stdClass();
f2ac0a3e
MN
1704 $conversation->type = $type;
1705 $conversation->name = $name;
1706 $conversation->convhash = null;
1707 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1708 $conversation->convhash = helper::get_conversation_hash($userids);
1709 }
76540bec
MN
1710 $conversation->component = $component;
1711 $conversation->itemtype = $itemtype;
1712 $conversation->itemid = $itemid;
1713 $conversation->contextid = $contextid;
1714 $conversation->enabled = $enabled;
883ce421 1715 $conversation->timecreated = time();
76540bec 1716 $conversation->timemodified = $conversation->timecreated;
883ce421
MN
1717 $conversation->id = $DB->insert_record('message_conversations', $conversation);
1718
f2ac0a3e
MN
1719 // Add users to this conversation.
1720 $arrmembers = [];
b2cd17e6
MN
1721 foreach ($userids as $userid) {
1722 $member = new \stdClass();
1723 $member->conversationid = $conversation->id;
1724 $member->userid = $userid;
1725 $member->timecreated = time();
f2ac0a3e
MN
1726 $member->id = $DB->insert_record('message_conversation_members', $member);
1727
1728 $arrmembers[] = $member;
b2cd17e6 1729 }
883ce421 1730
f2ac0a3e
MN
1731 $conversation->members = $arrmembers;
1732
1733 return $conversation;
883ce421 1734 }
0b3eadcd 1735
e66b915c
MN
1736 /**
1737 * Checks if a user can create a group conversation.
1738 *
1739 * @param int $userid The id of the user attempting to create the conversation
1740 * @param \context $context The context they are creating the conversation from, most likely course context
1741 * @return bool
1742 */
1743 public static function can_create_group_conversation(int $userid, \context $context) : bool {
1744 global $CFG;
1745
1746 // If we can't message at all, then we can't create a conversation.
1747 if (empty($CFG->messaging)) {
1748 return false;
1749 }
1750
1751 // We need to check they have the capability to create the conversation.
1752 return has_capability('moodle/course:creategroupconversations', $context, $userid);
883ce421 1753 }
0b3eadcd 1754
0d203bbf
MN
1755 /**
1756 * Checks if a user can create a contact request.
1757 *
1758 * @param int $userid The id of the user who is creating the contact request
1759 * @param int $requesteduserid The id of the user being requested
1760 * @return bool
1761 */
1762 public static function can_create_contact(int $userid, int $requesteduserid) : bool {
1763 global $CFG;
1764
1765 // If we can't message at all, then we can't create a contact.
1766 if (empty($CFG->messaging)) {
1767 return false;
1768 }
1769
1770 // If we can message anyone on the site then we can create a contact.
1771 if ($CFG->messagingallusers) {
1772 return true;
1773 }
1774
1775 // We need to check if they are in the same course.
1776 return enrol_sharing_course($userid, $requesteduserid);
1777 }
1778
0b3eadcd
MN
1779 /**
1780 * Handles creating a contact request.
1781 *
1782 * @param int $userid The id of the user who is creating the contact request
1783 * @param int $requesteduserid The id of the user being requested
1784 */
1785 public static function create_contact_request(int $userid, int $requesteduserid) {
1786 global $DB;
1787
1788 $request = new \stdClass();
1789 $request->userid = $userid;
1790 $request->requesteduserid = $requesteduserid;
1791 $request->timecreated = time();
1792
1793 $DB->insert_record('message_contact_requests', $request);
be016b01
MN
1794
1795 // Send a notification.
1796 $userfrom = \core_user::get_user($userid);
1797 $userfromfullname = fullname($userfrom);
1798 $userto = \core_user::get_user($requesteduserid);
1799 $url = new \moodle_url('/message/pendingcontactrequests.php');
1800
1801 $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
1802 $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);
1803
1804 $message = new \core\message\message();
1805 $message->courseid = SITEID;
1806 $message->component = 'moodle';
1807 $message->name = 'messagecontactrequests';
1808 $message->notification = 1;
1809 $message->userfrom = $userfrom;
1810 $message->userto = $userto;
1811 $message->subject = $subject;
1812 $message->fullmessage = text_to_html($fullmessage);
1813 $message->fullmessageformat = FORMAT_HTML;
1814 $message->fullmessagehtml = $fullmessage;
1815 $message->smallmessage = '';
1816 $message->contexturl = $url->out(false);
1817
1818 message_send($message);
0b3eadcd
MN
1819 }
1820
1821
1822 /**
1823 * Handles confirming a contact request.
1824 *
1825 * @param int $userid The id of the user who created the contact request
1826 * @param int $requesteduserid The id of the user confirming the request
1827 */
1828 public static function confirm_contact_request(int $userid, int $requesteduserid) {
1829 global $DB;
1830
1831 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1832 'requesteduserid' => $requesteduserid])) {
1833 self::add_contact($userid, $requesteduserid);
1834
1835 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1836 }
1837 }
1838
1839 /**
1840 * Handles declining a contact request.
1841 *
1842 * @param int $userid The id of the user who created the contact request
1843 * @param int $requesteduserid The id of the user declining the request
1844 */
1845 public static function decline_contact_request(int $userid, int $requesteduserid) {
1846 global $DB;
1847
1848 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1849 'requesteduserid' => $requesteduserid])) {
1850 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1851 }
1852 }
1853
1854 /**
1855 * Handles returning the contact requests for a user.
1856 *
1857 * This also includes the user data necessary to display information
1858 * about the user.
1859 *
1860 * It will not include blocked users.
1861 *
1862 * @param int $userid
1863 * @return array The list of contact requests
1864 */
1865 public static function get_contact_requests(int $userid) : array {
1866 global $DB;
1867
0b3eadcd 1868 $ufields = \user_picture::fields('u');
0b3eadcd
MN
1869 $sql = "SELECT $ufields, mcr.id as contactrequestid
1870 FROM {user} u
1871 JOIN {message_contact_requests} mcr
1872 ON u.id = mcr.userid
1873 LEFT JOIN {message_users_blocked} mub
1874 ON (mub.userid = ? AND mub.blockeduserid = u.id)
1875 WHERE mcr.requesteduserid = ?
1876 AND u.deleted = 0
1877 AND mub.id is NULL
1878 ORDER BY mcr.timecreated DESC";
1879
1880 return $DB->get_records_sql($sql, [$userid, $userid]);
1881 }
1882
1883 /**
1884 * Handles adding a contact.
1885 *
1886 * @param int $userid The id of the user who requested to be a contact
1887 * @param int $contactid The id of the contact
1888 */
1889 public static function add_contact(int $userid, int $contactid) {
1890 global $DB;
1891
1892 $messagecontact = new \stdClass();
1893 $messagecontact->userid = $userid;
1894 $messagecontact->contactid = $contactid;
1895 $messagecontact->timecreated = time();
1896 $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
1897
1898 $eventparams = [
1899 'objectid' => $messagecontact->id,
1900 'userid' => $userid,
1901 'relateduserid' => $contactid,
1902 'context' => \context_user::instance($userid)
1903 ];
1904 $event = \core\event\message_contact_added::create($eventparams);
1905 $event->add_record_snapshot('message_contacts', $messagecontact);
1906 $event->trigger();
1907 }
1908
1909 /**
1910 * Handles removing a contact.
1911 *
1912 * @param int $userid The id of the user who is removing a user as a contact
1913 * @param int $contactid The id of the user to be removed as a contact
1914 */
1915 public static function remove_contact(int $userid, int $contactid) {
1916 global $DB;
1917
1918 if ($contact = self::get_contact($userid, $contactid)) {
1919 $DB->delete_records('message_contacts', ['id' => $contact->id]);
1920
1921 $event = \core\event\message_contact_removed::create(array(
1922 'objectid' => $contact->id,
1923 'userid' => $userid,
1924 'relateduserid' => $contactid,
1925 'context' => \context_user::instance($userid)
1926 ));
1927 $event->add_record_snapshot('message_contacts', $contact);
1928 $event->trigger();
1929 }
1930 }
1931
1932 /**
1933 * Handles blocking a user.
1934 *
1935 * @param int $userid The id of the user who is blocking
1936 * @param int $usertoblockid The id of the user being blocked
1937 */
1938 public static function block_user(int $userid, int $usertoblockid) {
1939 global $DB;
1940
1941 $blocked = new \stdClass();
1942 $blocked->userid = $userid;
1943 $blocked->blockeduserid = $usertoblockid;
1944 $blocked->timecreated = time();
1945 $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
1946
1947 // Trigger event for blocking a contact.
1948 $event = \core\event\message_user_blocked::create(array(
1949 'objectid' => $blocked->id,
1950 'userid' => $userid,
1951 'relateduserid' => $usertoblockid,
1952 'context' => \context_user::instance($userid)
1953 ));
1954 $event->add_record_snapshot('message_users_blocked', $blocked);
1955 $event->trigger();
1956 }
1957
1958 /**
1959 * Handles unblocking a user.
1960 *
1961 * @param int $userid The id of the user who is unblocking
1962 * @param int $usertounblockid The id of the user being unblocked
1963 */
1964 public static function unblock_user(int $userid, int $usertounblockid) {
1965 global $DB;
1966
1967 if ($blockeduser = $DB->get_record('message_users_blocked',
1968 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
1969 $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
1970
1971 // Trigger event for unblocking a contact.
1972 $event = \core\event\message_user_unblocked::create(array(
1973 'objectid' => $blockeduser->id,
1974 'userid' => $userid,
1975 'relateduserid' => $usertounblockid,
1976 'context' => \context_user::instance($userid)
1977 ));
1978 $event->add_record_snapshot('message_users_blocked', $blockeduser);
1979 $event->trigger();
1980 }
1981 }
1982
1983 /**
1984 * Checks if users are already contacts.
1985 *
1986 * @param int $userid The id of one of the users
1987 * @param int $contactid The id of the other user
1988 * @return bool Returns true if they are a contact, false otherwise
1989 */
1990 public static function is_contact(int $userid, int $contactid) : bool {
1991 global $DB;
1992
1993 $sql = "SELECT id
1994 FROM {message_contacts} mc
1995 WHERE (mc.userid = ? AND mc.contactid = ?)
1996 OR (mc.userid = ? AND mc.contactid = ?)";
1997 return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
1998 }
1999
2000 /**
2001 * Returns the row in the database table message_contacts that represents the contact between two people.
2002 *
2003 * @param int $userid The id of one of the users
2004 * @param int $contactid The id of the other user
2005 * @return mixed A fieldset object containing the record, false otherwise
2006 */
2007 public static function get_contact(int $userid, int $contactid) {
2008 global $DB;
2009
2010 $sql = "SELECT mc.*
2011 FROM {message_contacts} mc
2012 WHERE (mc.userid = ? AND mc.contactid = ?)
2013 OR (mc.userid = ? AND mc.contactid = ?)";
2014 return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
2015 }
2016
2017 /**
2018 * Checks if a user is already blocked.
2019 *
0b3eadcd
MN
2020 * @param int $userid
2021 * @param int $blockeduserid
2022 * @return bool Returns true if they are a blocked, false otherwise
2023 */
2024 public static function is_blocked(int $userid, int $blockeduserid) : bool {
2025 global $DB;
2026
2027 return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
2028 }
2029
2030 /**
2031 * Checks if a contact request already exists between users.
2032 *
2033 * @param int $userid The id of the user who is creating the contact request
2034 * @param int $requesteduserid The id of the user being requested
2035 * @return bool Returns true if a contact request exists, false otherwise
2036 */
2037 public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
2038 global $DB;
2039
2040 $sql = "SELECT id
2041 FROM {message_contact_requests} mcr
2042 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
2043 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
2044 return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
2045 }
08cb8a34
MN
2046
2047 /**
2048 * Checks if a user is already in a conversation.
2049 *
2050 * @param int $userid The id of the user we want to check if they are in a group
2051 * @param int $conversationid The id of the conversation
2052 * @return bool Returns true if a contact request exists, false otherwise
2053 */
2054 public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
2055 global $DB;
2056
2057 return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
2058 'userid' => $userid]);
7983fb83
SA
2059 }
2060
2061 /**
2062 * Checks if the sender can message the recipient.
2063 *
2064 * @param \stdClass $recipient The user object.
2065 * @param \stdClass $sender The user object.
2066 * @return bool true if recipient hasn't blocked sender and sender can contact to recipient, false otherwise.
2067 */
2068 protected static function can_contact_user(\stdClass $recipient, \stdClass $sender) : bool {
7983fb83
SA
2069 if (has_capability('moodle/site:messageanyuser', \context_system::instance(), $sender->id)) {
2070 // The sender has the ability to contact any user across the entire site.
2071 return true;
2072 }
2073
2074 // The initial value of $cancontact is null to indicate that a value has not been determined.
2075 $cancontact = null;
2076
2077 if (self::is_blocked($recipient->id, $sender->id)) {
2078 // The recipient has specifically blocked this sender.
2079 $cancontact = false;
2080 }
2081
2082 $sharedcourses = null;
2083 if (null === $cancontact) {
2084 // There are three user preference options:
2085 // - Site: Allow anyone not explicitly blocked to contact me;
2086 // - Course members: Allow anyone I am in a course with to contact me; and
2087 // - Contacts: Only allow my contacts to contact me.
2088 //
2089 // The Site option is only possible when the messagingallusers site setting is also enabled.
2090
2091 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
2092 if (self::MESSAGE_PRIVACY_SITE === $privacypreference) {
2093 // The user preference is to allow any user to contact them.
2094 // No need to check anything else.
2095 $cancontact = true;
2096 } else {
2097 // This user only allows their own contacts, and possibly course peers, to contact them.
2098 // If the users are contacts then we can avoid the more expensive shared courses check.
2099 $cancontact = self::is_contact($sender->id, $recipient->id);
2100
2101 if (!$cancontact && self::MESSAGE_PRIVACY_COURSEMEMBER === $privacypreference) {
2102 // The users are not contacts and the user allows course member messaging.
2103 // Check whether these two users share any course together.
2104 $sharedcourses = enrol_get_shared_courses($recipient->id, $sender->id, true);
2105 $cancontact = (!empty($sharedcourses));
2106 }
2107 }
2108 }
2109
2110 if (false === $cancontact) {
2111 // At the moment the users cannot contact one another.
2112 // Check whether the messageanyuser capability applies in any of the shared courses.
2113 // This is intended to allow teachers to message students regardless of message settings.
2114
2115 // Note: You cannot use empty($sharedcourses) here because this may be an empty array.
2116 if (null === $sharedcourses) {
2117 $sharedcourses = enrol_get_shared_courses($recipient->id, $sender->id, true);
2118 }
2119
2120 foreach ($sharedcourses as $course) {
2121 // Note: enrol_get_shared_courses will preload any shared context.
2122 if (has_capability('moodle/site:messageanyuser', \context_course::instance($course->id), $sender->id)) {
2123 $cancontact = true;
2124 break;
2125 }
2126 }
2127 }
08cb8a34 2128
7983fb83 2129 return $cancontact;
08cb8a34 2130 }
67b81351 2131
623048af
AA
2132 /**
2133 * Add some new members to an existing conversation.
2134 *
2135 * @param array $userids User ids array to add as members.
2136 * @param int $convid The conversation id. Must exists.
2137 * @throws \dml_missing_record_exception If convid conversation doesn't exist
2138 * @throws \dml_exception If there is a database error
83e3a4fe 2139 * @throws \moodle_exception If trying to add a member(s) to a non-group conversation
623048af
AA
2140 */
2141 public static function add_members_to_conversation(array $userids, int $convid) {
2142 global $DB;
2143
2144 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2145
83e3a4fe
MN
2146 // We can only add members to a group conversation.
2147 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2148 throw new \moodle_exception('You can not add members to a non-group conversation.');
2149 }
2150
623048af
AA
2151 // Be sure we are not trying to add a non existing user to the conversation. Work only with existing users.
2152 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
4abe3d25 2153 $existingusers = $DB->get_fieldset_select('user', 'id', "id $useridcondition", $params);
623048af
AA
2154
2155 // Be sure we are not adding a user is already member of the conversation. Take all the members.
2156 $memberuserids = array_values($DB->get_records_menu(
2157 'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
2158 );
2159
2160 // Work with existing new members.
2161 $members = array();
2162 $newuserids = array_diff($existingusers, $memberuserids);
2163 foreach ($newuserids as $userid) {
2164 $member = new \stdClass();
2165 $member->conversationid = $convid;
2166 $member->userid = $userid;
2167 $member->timecreated = time();
2168 $members[] = $member;
2169 }
2170
623048af 2171 $DB->insert_records('message_conversation_members', $members);
623048af
AA
2172 }
2173
2174 /**
2175 * Remove some members from an existing conversation.
2176 *
2177 * @param array $userids The user ids to remove from conversation members.
2178 * @param int $convid The conversation id. Must exists.
2179 * @throws \dml_exception
83e3a4fe 2180 * @throws \moodle_exception If trying to remove a member(s) from a non-group conversation
623048af
AA
2181 */
2182 public static function remove_members_from_conversation(array $userids, int $convid) {
2183 global $DB;
2184
2185 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2186
83e3a4fe
MN
2187 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2188 throw new \moodle_exception('You can not remove members from a non-group conversation.');
2189 }
2190
623048af
AA
2191 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2192 $params['convid'] = $convid;
2193
623048af
AA
2194 $DB->delete_records_select('message_conversation_members',
2195 "conversationid = :convid AND userid $useridcondition", $params);
623048af
AA
2196 }
2197
2198 /**
2199 * Count conversation members.
2200 *
2201 * @param int $convid The conversation id.
2202 * @return int Number of conversation members.
2203 * @throws \dml_exception
2204 */
2205 public static function count_conversation_members(int $convid) : int {
2206 global $DB;
08cb8a34 2207
623048af 2208 return $DB->count_records('message_conversation_members', ['conversationid' => $convid]);
08cb8a34 2209 }
55fda006 2210
f0e137c5
MN
2211 /**
2212 * Checks whether or not a conversation area is enabled.
2213 *
2214 * @param string $component Defines the Moodle component which the area was added to.
2215 * @param string $itemtype Defines the type of the component.
2216 * @param int $itemid The id of the component.
2217 * @param int $contextid The id of the context.
2218 * @return bool Returns if a conversation area exists and is enabled, false otherwise
2219 */
2220 public static function is_conversation_area_enabled(string $component, string $itemtype, int $itemid, int $contextid) : bool {
2221 global $DB;
2222
76540bec 2223 return $DB->record_exists('message_conversations',
f0e137c5
MN
2224 [
2225 'itemid' => $itemid,
2226 'contextid' => $contextid,
2227 'component' => $component,
2228 'itemtype' => $itemtype,
76540bec 2229 'enabled' => self::MESSAGE_CONVERSATION_ENABLED
f0e137c5
MN
2230 ]
2231 );
2232 }
2233
e7f46714 2234 /**
76540bec 2235 * Get conversation by area.
e7f46714 2236 *
2237 * @param string $component Defines the Moodle component which the area was added to.
2238 * @param string $itemtype Defines the type of the component.
76540bec
MN
2239 * @param int $itemid The id of the component.
2240 * @param int $contextid The id of the context.
2241 * @return \stdClass
e7f46714 2242 */
76540bec 2243 public static function get_conversation_by_area(string $component, string $itemtype, int $itemid, int $contextid) {
e7f46714 2244 global $DB;
2245
76540bec 2246 return $DB->get_record('message_conversations',
f0e137c5
MN
2247 [
2248 'itemid' => $itemid,
2249 'contextid' => $contextid,
2250 'component' => $component,
2251 'itemtype' => $itemtype
2252 ]
2253 );
e7f46714 2254 }
2255
2256 /**
76540bec 2257 * Enable a conversation.
e7f46714 2258 *
76540bec 2259 * @param int $conversationid The id of the conversation.
e7f46714 2260 * @return void
2261 */
76540bec 2262 public static function enable_conversation(int $conversationid) {
e7f46714 2263 global $DB;
2264
76540bec
MN
2265 $conversation = new \stdClass();
2266 $conversation->id = $conversationid;
2267 $conversation->enabled = self::MESSAGE_CONVERSATION_ENABLED;
2268 $conversation->timemodified = time();
2269 $DB->update_record('message_conversations', $conversation);
e7f46714 2270 }
2271
2272 /**
76540bec 2273 * Disable a conversation.
e7f46714 2274 *
76540bec 2275 * @param int $conversationid The id of the conversation.
e7f46714 2276 * @return void
2277 */
76540bec 2278 public static function disable_conversation(int $conversationid) {
e7f46714 2279 global $DB;
2280
76540bec
MN
2281 $conversation = new \stdClass();
2282 $conversation->id = $conversationid;
2283 $conversation->enabled = self::MESSAGE_CONVERSATION_DISABLED;
2284 $conversation->timemodified = time();
2285 $DB->update_record('message_conversations', $conversation);
e7f46714 2286 }
2287
2288 /**
2289 * Update the name of a conversation.
2290 *
76540bec 2291 * @param int $conversationid The id of a conversation.
e7f46714 2292 * @param string $name The main name of the area
2293 * @return void
2294 */
2295 public static function update_conversation_name(int $conversationid, string $name) {
2296 global $DB;
2297
2298 if ($conversation = $DB->get_record('message_conversations', array('id' => $conversationid))) {
2299 if ($name <> $conversation->name) {
2300 $conversation->name = $name;
f0e137c5 2301 $conversation->timemodified = time();
e7f46714 2302 $DB->update_record('message_conversations', $conversation);
2303 }
2304 }
2305 }
6ecd6e5b
MN
2306
2307 /**
2308 * Returns a list of conversation members.
2309 *
2310 * @param int $userid The user we are returning the conversation members for, used by helper::get_member_info.
2311 * @param int $conversationid The id of the conversation
2312 * @param bool $includecontactrequests Do we want to include contact requests with this data?
2313 * @param int $limitfrom
2314 * @param int $limitnum
2315 * @return array
2316 */
2317 public static function get_conversation_members(int $userid, int $conversationid, bool $includecontactrequests = false,
2318 int $limitfrom = 0, int $limitnum = 0) : array {
2319 global $DB;
2320
2321 if ($members = $DB->get_records('message_conversation_members', ['conversationid' => $conversationid],
2322 'timecreated ASC, id ASC', 'userid', $limitfrom, $limitnum)) {
2323 $userids = array_keys($members);
2324 $members = helper::get_member_info($userid, $userids);
2325
2326 // Check if we want to include contact requests as well.
2327 if ($includecontactrequests) {
2328 list($useridsql, $usersparams) = $DB->get_in_or_equal($userids);
2329
2330 $wheresql = "(userid $useridsql OR requesteduserid $useridsql)";
2331 if ($contactrequests = $DB->get_records_select('message_contact_requests', $wheresql,
2332 array_merge($usersparams, $usersparams), 'timecreated ASC, id ASC')) {
2333 foreach ($contactrequests as $contactrequest) {
2334 if (isset($members[$contactrequest->userid])) {
2335 $members[$contactrequest->userid]->contactrequests[] = $contactrequest;
2336 }
2337 if (isset($members[$contactrequest->requesteduserid])) {
2338 $members[$contactrequest->requesteduserid]->contactrequests[] = $contactrequest;
2339 }
2340 }
2341 }
2342 }
2343
2344 return $members;
2345 }
2346
2347 return [];
2348 }
879e2bef 2349}