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