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