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