MDL-63303 core_favourites: add get and count functions
[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
1039 $arrmessages = array();
1040 if ($messages = helper::get_conversation_messages($userid, $convid, 0, $limitfrom, $limitnum, $sort, $timefrom, $timeto)) {
1041 $arrmessages = helper::format_conversation_messages($userid, $convid, $messages);
1042 }
1043
1044 return $arrmessages;
1045 }
1046
c060cd49
MN
1047 /**
1048 * Returns the most recent message between two users.
1049 *
4461288d
MN
1050 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1051 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1052 * Followup: MDL-63915
1053 *
c060cd49
MN
1054 * @param int $userid the current user
1055 * @param int $otheruserid the other user
de55cb1b 1056 * @return \stdClass|null
c060cd49
MN
1057 */
1058 public static function get_most_recent_message($userid, $otheruserid) {
1059 // We want two messages here so we get an accurate 'blocktime' value.
de55cb1b 1060 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
1061 // Swap the order so we now have them in historical order.
1062 $messages = array_reverse($messages);
de55cb1b 1063 $arrmessages = helper::create_messages($userid, $messages);
c060cd49
MN
1064 return array_pop($arrmessages);
1065 }
1066
1067 return null;
1068 }
c6e97f54 1069
fb04293b
SA
1070 /**
1071 * Returns the most recent message in a conversation.
1072 *
1073 * @param int $convid The conversation identifier.
1074 * @param int $currentuserid The current user identifier.
1075 * @return \stdClass|null The most recent message.
1076 */
1077 public static function get_most_recent_conversation_message(int $convid, int $currentuserid = 0) {
1078 global $USER;
1079
1080 if (empty($currentuserid)) {
1081 $currentuserid = $USER->id;
1082 }
1083
1084 if ($messages = helper::get_conversation_messages($currentuserid, $convid, 0, 0, 1, 'timecreated DESC')) {
1085 $convmessages = helper::format_conversation_messages($currentuserid, $convid, $messages);
1086 return array_pop($convmessages['messages']);
1087 }
1088
1089 return null;
1090 }
1091
c6e97f54
MN
1092 /**
1093 * Returns the profile information for a contact for a user.
1094 *
4461288d
MN
1095 * TODO: This function should be removed once the new group messaging UI is in place and the old messaging UI is removed.
1096 * For now we are not removing/deprecating this function for backwards compatibility with messaging UI.
1097 * Followup: MDL-63915
1098 *
c6e97f54
MN
1099 * @param int $userid The user id
1100 * @param int $otheruserid The id of the user whose profile we want to view.
de55cb1b 1101 * @return \stdClass
c6e97f54
MN
1102 */
1103 public static function get_profile($userid, $otheruserid) {
f219eac7 1104 global $CFG, $PAGE;
c6e97f54
MN
1105
1106 require_once($CFG->dirroot . '/user/lib.php');
1107
f4c39cb9
MN
1108 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
1109
1110 // Create the data we are going to pass to the renderable.
1111 $data = new \stdClass();
1112 $data->userid = $otheruserid;
1113 $data->fullname = fullname($user);
1114 $data->city = '';
1115 $data->country = '';
1116 $data->email = '';
cb805753 1117 $data->isonline = null;
f4c39cb9
MN
1118 // Get the user picture data - messaging has always shown these to the user.
1119 $userpicture = new \user_picture($user);
1120 $userpicture->size = 1; // Size f1.
1121 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
1122 $userpicture->size = 0; // Size f2.
1123 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
1124
1125 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
1126 if ($userfields) {
1127 if (isset($userfields['city'])) {
1128 $data->city = $userfields['city'];
1129 }
1130 if (isset($userfields['country'])) {
1131 $data->country = $userfields['country'];
bf58081d 1132 }
f4c39cb9
MN
1133 if (isset($userfields['email'])) {
1134 $data->email = $userfields['email'];
c6e97f54 1135 }
f4c39cb9
MN
1136 if (isset($userfields['lastaccess'])) {
1137 $data->isonline = helper::is_online($userfields['lastaccess']);
1138 }
1139 }
c6e97f54 1140
f219eac7
MN
1141 $data->isblocked = self::is_blocked($userid, $otheruserid);
1142 $data->iscontact = self::is_contact($userid, $otheruserid);
f4c39cb9
MN
1143
1144 return $data;
c6e97f54 1145 }
dec0cd99
MN
1146
1147 /**
1148 * Checks if a user can delete messages they have either received or sent.
1149 *
1150 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1151 * but will still seem as if it was by the user)
15663b0b 1152 * @param int $conversationid The id of the conversation
1f64514d 1153 * @return bool Returns true if a user can delete the conversation, false otherwise.
dec0cd99 1154 */
15663b0b 1155 public static function can_delete_conversation(int $userid, int $conversationid = null) : bool {
dec0cd99
MN
1156 global $USER;
1157
15663b0b
MN
1158 if (is_null($conversationid)) {
1159 debugging('\core_message\api::can_delete_conversation() now expects a \'conversationid\' to be passed.',
1160 DEBUG_DEVELOPER);
1161 return false;
1162 }
1163
dec0cd99
MN
1164 $systemcontext = \context_system::instance();
1165
15663b0b
MN
1166 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1167 return true;
1168 }
1169
1170 if (!self::is_user_in_conversation($userid, $conversationid)) {
1171 return false;
1172 }
1173
1174 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1175 $USER->id == $userid) {
dec0cd99
MN
1176 return true;
1177 }
1178
1179 return false;
1180 }
1181
1182 /**
1183 * Deletes a conversation.
1184 *
1185 * This function does not verify any permissions.
1186 *
263ad984 1187 * @deprecated since 3.6
dec0cd99
MN
1188 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1189 * but will still seem as if it was by the user)
1190 * @param int $otheruserid The id of the other user in the conversation
1191 * @return bool
1192 */
1193 public static function delete_conversation($userid, $otheruserid) {
263ad984
MN
1194 debugging('\core_message\api::delete_conversation() is deprecated, please use ' .
1195 '\core_message\api::delete_conversation_by_id() instead.', DEBUG_DEVELOPER);
dec0cd99 1196
b2cd17e6 1197 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
dec0cd99 1198
883ce421
MN
1199 // If there is no conversation, there is nothing to do.
1200 if (!$conversationid) {
1201 return true;
1202 }
1203
263ad984
MN
1204 self::delete_conversation_by_id($userid, $conversationid);
1205
1206 return true;
1207 }
1208
1209 /**
1210 * Deletes a conversation for a specified user.
1211 *
1212 * This function does not verify any permissions.
1213 *
1214 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
1215 * but will still seem as if it was by the user)
1216 * @param int $conversationid The id of the other user in the conversation
1217 */
1218 public static function delete_conversation_by_id(int $userid, int $conversationid) {
1219 global $DB, $USER;
1220
883ce421
MN
1221 // Get all messages belonging to this conversation that have not already been deleted by this user.
1222 $sql = "SELECT m.*
1223 FROM {messages} m
1224 INNER JOIN {message_conversations} mc
1225 ON m.conversationid = mc.id
1226 LEFT JOIN {message_user_actions} mua
1227 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1228 WHERE mua.id is NULL
1229 AND mc.id = ?
1230 ORDER BY m.timecreated ASC";
1231 $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
1232
1233 // Ok, mark these as deleted.
1234 foreach ($messages as $message) {
1235 $mua = new \stdClass();
1236 $mua->userid = $userid;
1237 $mua->messageid = $message->id;
1238 $mua->action = self::MESSAGE_ACTION_DELETED;
1239 $mua->timecreated = time();
1240 $mua->id = $DB->insert_record('message_user_actions', $mua);
1241
14de10c4
MN
1242 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1243 $message->id, $mua->id)->trigger();
dec0cd99 1244 }
dec0cd99 1245 }
79f6c36c
MN
1246
1247 /**
1248 * Returns the count of unread conversations (collection of messages from a single user) for
1249 * the given user.
1250 *
1251 * @param \stdClass $user the user who's conversations should be counted
1252 * @return int the count of the user's unread conversations
1253 */
1254 public static function count_unread_conversations($user = null) {
1255 global $USER, $DB;
1256
1257 if (empty($user)) {
1258 $user = $USER;
1259 }
1260
883ce421
MN
1261 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
1262 FROM {messages} m
1263 INNER JOIN {message_conversations} mc
1264 ON m.conversationid = mc.id
1265 INNER JOIN {message_conversation_members} mcm
1266 ON mc.id = mcm.conversationid
1267 LEFT JOIN {message_user_actions} mua
1268 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1269 WHERE mcm.userid = ?
1270 AND mcm.userid != m.useridfrom
1271 AND mua.id is NULL";
1272
1273 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
79f6c36c
MN
1274 }
1275
abf7a261
MN
1276 /**
1277 * Checks if a user can mark all messages as read.
1278 *
1279 * @param int $userid The user id of who we want to mark the messages for
1280 * @param int $conversationid The id of the conversation
1281 * @return bool true if user is permitted, false otherwise
1282 * @since 3.6
1283 */
1284 public static function can_mark_all_messages_as_read(int $userid, int $conversationid) : bool {
1285 global $USER;
1286
1287 $systemcontext = \context_system::instance();
1288
1289 if (has_capability('moodle/site:readallmessages', $systemcontext)) {
1290 return true;
1291 }
1292
1293 if (!self::is_user_in_conversation($userid, $conversationid)) {
1294 return false;
1295 }
1296
1297 if ($USER->id == $userid) {
1298 return true;
1299 }
1300
1301 return false;
1302 }
1303
79f6c36c 1304 /**
74ad60bf 1305 * Marks all messages being sent to a user in a particular conversation.
79f6c36c 1306 *
74ad60bf 1307 * If $conversationdid is null then it marks all messages as read sent to $userid.
79f6c36c 1308 *
74ad60bf
MN
1309 * @param int $userid
1310 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
79f6c36c 1311 */
74ad60bf 1312 public static function mark_all_messages_as_read($userid, $conversationid = null) {
79f6c36c
MN
1313 global $DB;
1314
883ce421
MN
1315 $messagesql = "SELECT m.*
1316 FROM {messages} m
1317 INNER JOIN {message_conversations} mc
1318 ON mc.id = m.conversationid
1319 INNER JOIN {message_conversation_members} mcm
1320 ON mcm.conversationid = mc.id
5aac33c7
MN
1321 LEFT JOIN {message_user_actions} mua
1322 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
1323 WHERE mua.id is NULL
1324 AND mcm.userid = ?
74ad60bf 1325 AND m.useridfrom != ?";
5aac33c7
MN
1326 $messageparams = [];
1327 $messageparams[] = $userid;
1328 $messageparams[] = self::MESSAGE_ACTION_READ;
74ad60bf
MN
1329 $messageparams[] = $userid;
1330 $messageparams[] = $userid;
1331 if (!is_null($conversationid)) {
1332 $messagesql .= " AND mc.id = ?";
1333 $messageparams[] = $conversationid;
79f6c36c
MN
1334 }
1335
74ad60bf
MN
1336 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
1337 foreach ($messages as $message) {
1338 self::mark_message_as_read($userid, $message);
1339 }
1340 $messages->close();
1341 }
1342
1343 /**
1344 * Marks all notifications being sent from one user to another user as read.
1345 *
1346 * If the from user is null then it marks all notifications as read sent to the to user.
1347 *
1348 * @param int $touserid the id of the message recipient
1349 * @param int|null $fromuserid the id of the message sender, null if all messages
1350 * @return void
1351 */
1352 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
1353 global $DB;
1354
883ce421
MN
1355 $notificationsql = "SELECT n.*
1356 FROM {notifications} n
74ad60bf
MN
1357 WHERE useridto = ?
1358 AND timeread is NULL";
883ce421 1359 $notificationsparams = [$touserid];
79f6c36c 1360 if (!empty($fromuserid)) {
883ce421
MN
1361 $notificationsql .= " AND useridfrom = ?";
1362 $notificationsparams[] = $fromuserid;
79f6c36c
MN
1363 }
1364
74ad60bf
MN
1365 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
1366 foreach ($notifications as $notification) {
1367 self::mark_notification_as_read($notification);
79f6c36c 1368 }
74ad60bf
MN
1369 $notifications->close();
1370 }
79f6c36c 1371
74ad60bf
MN
1372 /**
1373 * Marks ALL messages being sent from $fromuserid to $touserid as read.
1374 *
1375 * Can be filtered by type.
1376 *
1377 * @deprecated since 3.5
1378 * @param int $touserid the id of the message recipient
1379 * @param int $fromuserid the id of the message sender
1380 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
1381 * @return void
1382 */
1383 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
1384 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
1385 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
1386 DEBUG_DEVELOPER);
1387
1388 $type = strtolower($type);
1389
1390 $conversationid = null;
1391 $ignoremessages = false;
1392 if (!empty($fromuserid)) {
99248f61 1393 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
74ad60bf
MN
1394 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
1395 $ignoremessages = true;
1396 }
79f6c36c
MN
1397 }
1398
74ad60bf
MN
1399 if (!empty($type)) {
1400 if ($type == MESSAGE_TYPE_NOTIFICATION) {
99248f61 1401 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf
MN
1402 } else if ($type == MESSAGE_TYPE_MESSAGE) {
1403 if (!$ignoremessages) {
99248f61 1404 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf
MN
1405 }
1406 }
1407 } else { // We want both.
99248f61 1408 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf 1409 if (!$ignoremessages) {
99248f61 1410 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf 1411 }
883ce421 1412 }
79f6c36c
MN
1413 }
1414
79f6c36c
MN
1415 /**
1416 * Returns message preferences.
1417 *
1418 * @param array $processors
1419 * @param array $providers
1420 * @param \stdClass $user
1421 * @return \stdClass
1422 * @since 3.2
1423 */
1424 public static function get_all_message_preferences($processors, $providers, $user) {
1425 $preferences = helper::get_providers_preferences($providers, $user->id);
1426 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
1427
1428 // For every processors put its options on the form (need to get function from processor's lib.php).
1429 foreach ($processors as $processor) {
1430 $processor->object->load_data($preferences, $user->id);
1431 }
1432
1433 // Load general messaging preferences.
f7dfa9ba 1434 $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
79f6c36c
MN
1435 $preferences->mailformat = $user->mailformat;
1436 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
1437
1438 return $preferences;
1439 }
5b0769db
MN
1440
1441 /**
1442 * Count the number of users blocked by a user.
1443 *
1444 * @param \stdClass $user The user object
1445 * @return int the number of blocked users
1446 */
1447 public static function count_blocked_users($user = null) {
1448 global $USER, $DB;
1449
1450 if (empty($user)) {
1451 $user = $USER;
1452 }
1453
f219eac7
MN
1454 $sql = "SELECT count(mub.id)
1455 FROM {message_users_blocked} mub
1456 WHERE mub.userid = :userid";
5b0769db
MN
1457 return $DB->count_records_sql($sql, array('userid' => $user->id));
1458 }
1459
1460 /**
1461 * Determines if a user is permitted to send another user a private message.
1462 * If no sender is provided then it defaults to the logged in user.
1463 *
1464 * @param \stdClass $recipient The user object.
1465 * @param \stdClass|null $sender The user object.
1466 * @return bool true if user is permitted, false otherwise.
1467 */
1468 public static function can_post_message($recipient, $sender = null) {
1469 global $USER;
1470
1471 if (is_null($sender)) {
1472 // The message is from the logged in user, unless otherwise specified.
1473 $sender = $USER;
1474 }
1475
7983fb83
SA
1476 $systemcontext = \context_system::instance();
1477 if (!has_capability('moodle/site:sendmessage', $systemcontext, $sender)) {
5b0769db
MN
1478 return false;
1479 }
1480
7983fb83 1481 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender->id)) {
c886e2c9
MN
1482 return true;
1483 }
1484
7983fb83 1485 // Check if the recipient can be messaged by the sender.
9f82758c 1486 return (self::can_contact_user($recipient->id, $sender->id));
5b0769db
MN
1487 }
1488
8e3bf150
JD
1489 /**
1490 * Determines if a user is permitted to send a message to a given conversation.
1491 * If no sender is provided then it defaults to the logged in user.
1492 *
1493 * @param int $userid the id of the user on which the checks will be applied.
1494 * @param int $conversationid the id of the conversation we wish to check.
1495 * @return bool true if the user can send a message to the conversation, false otherwise.
1496 * @throws \moodle_exception
1497 */
1498 public static function can_send_message_to_conversation(int $userid, int $conversationid) : bool {
1499 global $DB;
1500
1501 $systemcontext = \context_system::instance();
1502 if (!has_capability('moodle/site:sendmessage', $systemcontext, $userid)) {
1503 return false;
1504 }
1505
1506 if (!self::is_user_in_conversation($userid, $conversationid)) {
1507 return false;
1508 }
1509
1510 // User can post messages and is in the conversation, but we need to check the conversation type to
1511 // know whether or not to check the user privacy settings via can_contact_user().
1512 $conversation = $DB->get_record('message_conversations', ['id' => $conversationid], '*', MUST_EXIST);
1513 if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
1514 return true;
1515 } else if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1516 // Get the other user in the conversation.
1517 $members = self::get_conversation_members($userid, $conversationid);
1518 $otheruser = array_filter($members, function($member) use($userid) {
1519 return $member->id != $userid;
1520 });
1521 $otheruser = reset($otheruser);
1522
9f82758c 1523 return self::can_contact_user($otheruser->id, $userid);
8e3bf150
JD
1524 } else {
1525 throw new \moodle_exception("Invalid conversation type '$conversation->type'.");
1526 }
1527 }
1528
52f9cf20
JD
1529 /**
1530 * Send a message from a user to a conversation.
1531 *
1532 * This method will create the basic eventdata and delegate to message creation to message_send.
1533 * The message_send() method is responsible for event data that is specific to each recipient.
1534 *
1535 * @param int $userid the sender id.
1536 * @param int $conversationid the conversation id.
1537 * @param string $message the message to send.
1538 * @param int $format the format of the message to send.
1539 * @return \stdClass the message created.
1540 * @throws \coding_exception
1541 * @throws \moodle_exception if the user is not permitted to send a message to the conversation.
1542 */
1543 public static function send_message_to_conversation(int $userid, int $conversationid, string $message,
1544 int $format) : \stdClass {
1545 global $DB;
1546
1547 if (!self::can_send_message_to_conversation($userid, $conversationid)) {
1548 throw new \moodle_exception("User $userid cannot send a message to conversation $conversationid");
1549 }
1550
1551 $eventdata = new \core\message\message();
1552 $eventdata->courseid = 1;
1553 $eventdata->component = 'moodle';
1554 $eventdata->name = 'instantmessage';
1555 $eventdata->userfrom = $userid;
1556 $eventdata->convid = $conversationid;
1557
1558 if ($format == FORMAT_HTML) {
1559 $eventdata->fullmessagehtml = $message;
1560 // Some message processors may revert to sending plain text even if html is supplied,
1561 // so we keep both plain and html versions if we're intending to send html.
1562 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
1563 } else {
1564 $eventdata->fullmessage = $message;
1565 $eventdata->fullmessagehtml = '';
1566 }
1567
1568 $eventdata->fullmessageformat = $format;
1569 $eventdata->smallmessage = $message; // Store the message unfiltered. Clean up on output.
1570
1571 $eventdata->timecreated = time();
1572 $eventdata->notification = 0;
1573 $messageid = message_send($eventdata);
1574
1575 $messagerecord = $DB->get_record('messages', ['id' => $messageid], 'id, useridfrom, fullmessage, timecreated');
1576 $message = (object) [
1577 'id' => $messagerecord->id,
1578 'useridfrom' => $messagerecord->useridfrom,
1579 'text' => $messagerecord->fullmessage,
1580 'timecreated' => $messagerecord->timecreated
1581 ];
1582 return $message;
5b0769db
MN
1583 }
1584
f7dfa9ba
SA
1585 /**
1586 * Get the messaging preference for a user.
1587 * If the user has not any messaging privacy preference:
1588 * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
1589 * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
1590 *
1591 * @param int $userid The user identifier.
1592 * @return int The default messaging preference.
1593 */
1594 public static function get_user_privacy_messaging_preference(int $userid) : int {
1595 global $CFG;
1596
1597 // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
1598 // otherwise, the default value will be "My contacts and anyone in my courses".
1599 if (empty($CFG->messagingallusers)) {
1600 $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
1601 } else {
1602 $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
1603 }
1604 $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $userid);
1605
1606 // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
1607 // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1608 if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
1609 $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
1610 }
1611
1612 return $privacypreference;
1613 }
1614
5b0769db
MN
1615 /**
1616 * Checks if the recipient is allowing messages from users that aren't a
1617 * contact. If not then it checks to make sure the sender is in the
1618 * recipient's contacts.
1619 *
e5eba802 1620 * @deprecated since 3.6
5b0769db
MN
1621 * @param \stdClass $recipient The user object.
1622 * @param \stdClass|null $sender The user object.
1623 * @return bool true if $sender is blocked, false otherwise.
1624 */
1625 public static function is_user_non_contact_blocked($recipient, $sender = null) {
e5eba802
SA
1626 debugging('\core_message\api::is_user_non_contact_blocked() is deprecated', DEBUG_DEVELOPER);
1627
f7dfa9ba 1628 global $USER, $CFG;
5b0769db
MN
1629
1630 if (is_null($sender)) {
1631 // The message is from the logged in user, unless otherwise specified.
1632 $sender = $USER;
1633 }
1634
f7dfa9ba
SA
1635 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1636 switch ($privacypreference) {
1637 case self::MESSAGE_PRIVACY_SITE:
1638 if (!empty($CFG->messagingallusers)) {
1639 // Users can be messaged without being contacts or members of the same course.
1640 break;
1641 }
1642 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1643 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1644 case self::MESSAGE_PRIVACY_COURSEMEMBER:
1645 // Confirm the sender and the recipient are both members of the same course.
1646 if (enrol_sharing_course($recipient, $sender)) {
1647 // All good, the recipient and the sender are members of the same course.
1648 return false;
1649 }
1650 case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1651 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1652 return !self::is_contact($sender->id, $recipient->id);
5b0769db
MN
1653 }
1654
1655 return false;
1656 }
1657
1658 /**
1659 * Checks if the recipient has specifically blocked the sending user.
1660 *
1661 * Note: This function will always return false if the sender has the
1662 * readallmessages capability at the system context level.
1663 *
c886e2c9 1664 * @deprecated since 3.6
26dca05d
JP
1665 * @param int $recipientid User ID of the recipient.
1666 * @param int $senderid User ID of the sender.
5b0769db
MN
1667 * @return bool true if $sender is blocked, false otherwise.
1668 */
26dca05d 1669 public static function is_user_blocked($recipientid, $senderid = null) {
c886e2c9
MN
1670 debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1671 DEBUG_DEVELOPER);
1672
1673 global $USER;
5b0769db 1674
26dca05d 1675 if (is_null($senderid)) {
5b0769db 1676 // The message is from the logged in user, unless otherwise specified.
26dca05d 1677 $senderid = $USER->id;
5b0769db
MN
1678 }
1679
1680 $systemcontext = \context_system::instance();
26dca05d 1681 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
5b0769db
MN
1682 return false;
1683 }
1684
f219eac7 1685 if (self::is_blocked($recipientid, $senderid)) {
26dca05d 1686 return true;
5b0769db
MN
1687 }
1688
1689 return false;
1690 }
20ab51fd
AA
1691
1692 /**
1693 * Get specified message processor, validate corresponding plugin existence and
1694 * system configuration.
1695 *
1696 * @param string $name Name of the processor.
1697 * @param bool $ready only return ready-to-use processors.
1698 * @return mixed $processor if processor present else empty array.
1699 * @since Moodle 3.2
1700 */
1701 public static function get_message_processor($name, $ready = false) {
1702 global $DB, $CFG;
1703
1704 $processor = $DB->get_record('message_processors', array('name' => $name));
1705 if (empty($processor)) {
1706 // Processor not found, return.
1707 return array();
1708 }
1709
1710 $processor = self::get_processed_processor_object($processor);
1711 if ($ready) {
1712 if ($processor->enabled && $processor->configured) {
1713 return $processor;
1714 } else {
1715 return array();
1716 }
1717 } else {
1718 return $processor;
1719 }
1720 }
1721
1722 /**
1723 * Returns weather a given processor is enabled or not.
1724 * Note:- This doesn't check if the processor is configured or not.
1725 *
1726 * @param string $name Name of the processor
1727 * @return bool
1728 */
1729 public static function is_processor_enabled($name) {
1730
1731 $cache = \cache::make('core', 'message_processors_enabled');
1732 $status = $cache->get($name);
1733
1734 if ($status === false) {
1735 $processor = self::get_message_processor($name);
1736 if (!empty($processor)) {
1737 $cache->set($name, $processor->enabled);
1738 return $processor->enabled;
1739 } else {
1740 return false;
1741 }
1742 }
1743
1744 return $status;
1745 }
1746
1747 /**
1748 * Set status of a processor.
1749 *
1750 * @param \stdClass $processor processor record.
1751 * @param 0|1 $enabled 0 or 1 to set the processor status.
1752 * @return bool
1753 * @since Moodle 3.2
1754 */
1755 public static function update_processor_status($processor, $enabled) {
1756 global $DB;
1757 $cache = \cache::make('core', 'message_processors_enabled');
1758 $cache->delete($processor->name);
1759 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1760 }
1761
1762 /**
1763 * Given a processor object, loads information about it's settings and configurations.
1764 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1765 * or @see \get_message_processors()
1766 *
1767 * @param \stdClass $processor processor object
1768 * @return \stdClass processed processor object
1769 * @since Moodle 3.2
1770 */
1771 public static function get_processed_processor_object(\stdClass $processor) {
1772 global $CFG;
1773
1774 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1775 if (is_readable($processorfile)) {
1776 include_once($processorfile);
1777 $processclass = 'message_output_' . $processor->name;
1778 if (class_exists($processclass)) {
1779 $pclass = new $processclass();
1780 $processor->object = $pclass;
1781 $processor->configured = 0;
1782 if ($pclass->is_system_configured()) {
1783 $processor->configured = 1;
1784 }
1785 $processor->hassettings = 0;
1786 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1787 $processor->hassettings = 1;
1788 }
1789 $processor->available = 1;
1790 } else {
1791 print_error('errorcallingprocessor', 'message');
1792 }
1793 } else {
1794 $processor->available = 0;
1795 }
1796 return $processor;
1797 }
883ce421
MN
1798
1799 /**
1800 * Retrieve users blocked by $user1
1801 *
1802 * @param int $userid The user id of the user whos blocked users we are returning
1803 * @return array the users blocked
1804 */
1805 public static function get_blocked_users($userid) {
1806 global $DB;
1807
1808 $userfields = \user_picture::fields('u', array('lastaccess'));
1809 $blockeduserssql = "SELECT $userfields
f219eac7 1810 FROM {message_users_blocked} mub
883ce421 1811 INNER JOIN {user} u
f219eac7 1812 ON u.id = mub.blockeduserid
883ce421 1813 WHERE u.deleted = 0
f219eac7 1814 AND mub.userid = ?
883ce421
MN
1815 GROUP BY $userfields
1816 ORDER BY u.firstname ASC";
1817 return $DB->get_records_sql($blockeduserssql, [$userid]);
1818 }
1819
1820 /**
1821 * Mark a single message as read.
1822 *
1823 * @param int $userid The user id who marked the message as read
548936a6 1824 * @param \stdClass $message The message
883ce421
MN
1825 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1826 */
548936a6 1827 public static function mark_message_as_read($userid, $message, $timeread = null) {
883ce421
MN
1828 global $DB;
1829
1830 if (is_null($timeread)) {
1831 $timeread = time();
1832 }
1833
5aac33c7
MN
1834 $mua = new \stdClass();
1835 $mua->userid = $userid;
1836 $mua->messageid = $message->id;
1837 $mua->action = self::MESSAGE_ACTION_READ;
1838 $mua->timecreated = $timeread;
1839 $mua->id = $DB->insert_record('message_user_actions', $mua);
1840
1841 // Get the context for the user who received the message.
1842 $context = \context_user::instance($userid, IGNORE_MISSING);
1843 // If the user no longer exists the context value will be false, in this case use the system context.
1844 if ($context === false) {
1845 $context = \context_system::instance();
883ce421 1846 }
5aac33c7
MN
1847
1848 // Trigger event for reading a message.
1849 $event = \core\event\message_viewed::create(array(
1850 'objectid' => $mua->id,
1851 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1852 'context' => $context,
1853 'relateduserid' => $message->useridfrom,
1854 'other' => array(
1855 'messageid' => $message->id
1856 )
1857 ));
1858 $event->trigger();
883ce421
MN
1859 }
1860
1861 /**
1862 * Mark a single notification as read.
1863 *
548936a6 1864 * @param \stdClass $notification The notification
883ce421
MN
1865 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1866 */
548936a6 1867 public static function mark_notification_as_read($notification, $timeread = null) {
883ce421
MN
1868 global $DB;
1869
1870 if (is_null($timeread)) {
1871 $timeread = time();
1872 }
1873
883ce421
MN
1874 if (is_null($notification->timeread)) {
1875 $updatenotification = new \stdClass();
1876 $updatenotification->id = $notification->id;
1877 $updatenotification->timeread = $timeread;
1878
1879 $DB->update_record('notifications', $updatenotification);
376a79c2
MN
1880
1881 // Trigger event for reading a notification.
1882 \core\event\notification_viewed::create_from_ids(
1883 $notification->useridfrom,
1884 $notification->useridto,
1885 $notification->id
1886 )->trigger();
883ce421
MN
1887 }
1888 }
1889
1890 /**
1891 * Checks if a user can delete a message.
1892 *
1893 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1894 * but will still seem as if it was by the user)
1895 * @param int $messageid The message id
1896 * @return bool Returns true if a user can delete the message, false otherwise.
1897 */
1898 public static function can_delete_message($userid, $messageid) {
1899 global $DB, $USER;
1900
08cb8a34
MN
1901 $systemcontext = \context_system::instance();
1902
1903 $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
1904
1905 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1906 return true;
883ce421
MN
1907 }
1908
08cb8a34
MN
1909 if (!self::is_user_in_conversation($userid, $conversationid)) {
1910 return false;
1911 }
883ce421 1912
08cb8a34
MN
1913 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1914 $USER->id == $userid) {
883ce421
MN
1915 return true;
1916 }
1917
1918 return false;
1919 }
1920
1921 /**
1922 * Deletes a message.
1923 *
1924 * This function does not verify any permissions.
1925 *
1926 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1927 * but will still seem as if it was by the user)
1928 * @param int $messageid The message id
1929 * @return bool
1930 */
1931 public static function delete_message($userid, $messageid) {
14de10c4 1932 global $DB, $USER;
883ce421 1933
14de10c4
MN
1934 if (!$DB->record_exists('messages', ['id' => $messageid])) {
1935 return false;
1936 }
883ce421
MN
1937
1938 // Check if the user has already deleted this message.
1939 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1940 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1941 $mua = new \stdClass();
1942 $mua->userid = $userid;
1943 $mua->messageid = $messageid;
1944 $mua->action = self::MESSAGE_ACTION_DELETED;
1945 $mua->timecreated = time();
1946 $mua->id = $DB->insert_record('message_user_actions', $mua);
1947
1948 // Trigger event for deleting a message.
14de10c4
MN
1949 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1950 $messageid, $mua->id)->trigger();
883ce421
MN
1951
1952 return true;
1953 }
1954
1955 return false;
1956 }
1957
1958 /**
1959 * Returns the conversation between two users.
1960 *
b2cd17e6 1961 * @param array $userids
883ce421
MN
1962 * @return int|bool The id of the conversation, false if not found
1963 */
b2cd17e6 1964 public static function get_conversation_between_users(array $userids) {
883ce421
MN
1965 global $DB;
1966
b2cd17e6 1967 $hash = helper::get_conversation_hash($userids);
883ce421 1968
f2ac0a3e
MN
1969 $params = [
1970 'type' => self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1971 'convhash' => $hash
1972 ];
1973 if ($conversation = $DB->get_record('message_conversations', $params)) {
883ce421
MN
1974 return $conversation->id;
1975 }
1976
1977 return false;
1978 }
1979
1980 /**
1981 * Creates a conversation between two users.
1982 *
a66ae849 1983 * @deprecated since 3.6
b2cd17e6 1984 * @param array $userids
883ce421
MN
1985 * @return int The id of the conversation
1986 */
b2cd17e6 1987 public static function create_conversation_between_users(array $userids) {
a66ae849
MN
1988 debugging('\core_message\api::create_conversation_between_users is deprecated, please use ' .
1989 '\core_message\api::create_conversation instead.', DEBUG_DEVELOPER);
1990
f2ac0a3e
MN
1991 // This method was always used for individual conversations.
1992 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
1993
1994 return $conversation->id;
1995 }
1996
1997 /**
1998 * Creates a conversation with selected users and messages.
1999 *
2000 * @param int $type The type of conversation
2001 * @param int[] $userids The array of users to add to the conversation
76540bec
MN
2002 * @param string|null $name The name of the conversation
2003 * @param int $enabled Determines if the conversation is created enabled or disabled
2004 * @param string|null $component Defines the Moodle component which the conversation belongs to, if any
2005 * @param string|null $itemtype Defines the type of the component
2006 * @param int|null $itemid The id of the component
2007 * @param int|null $contextid The id of the context
f2ac0a3e
MN
2008 * @return \stdClass
2009 */
76540bec
MN
2010 public static function create_conversation(int $type, array $userids, string $name = null,
2011 int $enabled = self::MESSAGE_CONVERSATION_ENABLED, string $component = null,
2012 string $itemtype = null, int $itemid = null, int $contextid = null) {
2013
883ce421
MN
2014 global $DB;
2015
869eac82
MN
2016 $validtypes = [
2017 self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
2018 self::MESSAGE_CONVERSATION_TYPE_GROUP
2019 ];
2020
2021 if (!in_array($type, $validtypes)) {
2022 throw new \moodle_exception('An invalid conversation type was specified.');
2023 }
2024
f2ac0a3e
MN
2025 // Sanity check.
2026 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
2027 if (count($userids) > 2) {
2028 throw new \moodle_exception('An individual conversation can not have more than two users.');
2029 }
2030 }
2031
883ce421 2032 $conversation = new \stdClass();
f2ac0a3e
MN
2033 $conversation->type = $type;
2034 $conversation->name = $name;
2035 $conversation->convhash = null;
2036 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
2037 $conversation->convhash = helper::get_conversation_hash($userids);
2038 }
76540bec
MN
2039 $conversation->component = $component;
2040 $conversation->itemtype = $itemtype;
2041 $conversation->itemid = $itemid;
2042 $conversation->contextid = $contextid;
2043 $conversation->enabled = $enabled;
883ce421 2044 $conversation->timecreated = time();
76540bec 2045 $conversation->timemodified = $conversation->timecreated;
883ce421
MN
2046 $conversation->id = $DB->insert_record('message_conversations', $conversation);
2047
f2ac0a3e
MN
2048 // Add users to this conversation.
2049 $arrmembers = [];
b2cd17e6
MN
2050 foreach ($userids as $userid) {
2051 $member = new \stdClass();
2052 $member->conversationid = $conversation->id;
2053 $member->userid = $userid;
2054 $member->timecreated = time();
f2ac0a3e
MN
2055 $member->id = $DB->insert_record('message_conversation_members', $member);
2056
2057 $arrmembers[] = $member;
b2cd17e6 2058 }
883ce421 2059
f2ac0a3e
MN
2060 $conversation->members = $arrmembers;
2061
2062 return $conversation;
883ce421 2063 }
0b3eadcd 2064
e66b915c
MN
2065 /**
2066 * Checks if a user can create a group conversation.
2067 *
2068 * @param int $userid The id of the user attempting to create the conversation
2069 * @param \context $context The context they are creating the conversation from, most likely course context
2070 * @return bool
2071 */
2072 public static function can_create_group_conversation(int $userid, \context $context) : bool {
2073 global $CFG;
2074
2075 // If we can't message at all, then we can't create a conversation.
2076 if (empty($CFG->messaging)) {
2077 return false;
2078 }
2079
2080 // We need to check they have the capability to create the conversation.
2081 return has_capability('moodle/course:creategroupconversations', $context, $userid);
883ce421 2082 }
0b3eadcd 2083
0d203bbf
MN
2084 /**
2085 * Checks if a user can create a contact request.
2086 *
2087 * @param int $userid The id of the user who is creating the contact request
2088 * @param int $requesteduserid The id of the user being requested
2089 * @return bool
2090 */
2091 public static function can_create_contact(int $userid, int $requesteduserid) : bool {
2092 global $CFG;
2093
2094 // If we can't message at all, then we can't create a contact.
2095 if (empty($CFG->messaging)) {
2096 return false;
2097 }
2098
2099 // If we can message anyone on the site then we can create a contact.
2100 if ($CFG->messagingallusers) {
2101 return true;
2102 }
2103
2104 // We need to check if they are in the same course.
2105 return enrol_sharing_course($userid, $requesteduserid);
2106 }
2107
0b3eadcd
MN
2108 /**
2109 * Handles creating a contact request.
2110 *
2111 * @param int $userid The id of the user who is creating the contact request
2112 * @param int $requesteduserid The id of the user being requested
2113 */
2114 public static function create_contact_request(int $userid, int $requesteduserid) {
2115 global $DB;
2116
2117 $request = new \stdClass();
2118 $request->userid = $userid;
2119 $request->requesteduserid = $requesteduserid;
2120 $request->timecreated = time();
2121
2122 $DB->insert_record('message_contact_requests', $request);
be016b01
MN
2123
2124 // Send a notification.
2125 $userfrom = \core_user::get_user($userid);
2126 $userfromfullname = fullname($userfrom);
2127 $userto = \core_user::get_user($requesteduserid);
2128 $url = new \moodle_url('/message/pendingcontactrequests.php');
2129
2130 $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
2131 $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);
2132
2133 $message = new \core\message\message();
2134 $message->courseid = SITEID;
2135 $message->component = 'moodle';
2136 $message->name = 'messagecontactrequests';
2137 $message->notification = 1;
2138 $message->userfrom = $userfrom;
2139 $message->userto = $userto;
2140 $message->subject = $subject;
2141 $message->fullmessage = text_to_html($fullmessage);
2142 $message->fullmessageformat = FORMAT_HTML;
2143 $message->fullmessagehtml = $fullmessage;
2144 $message->smallmessage = '';
2145 $message->contexturl = $url->out(false);
2146
2147 message_send($message);
0b3eadcd
MN
2148 }
2149
2150
2151 /**
2152 * Handles confirming a contact request.
2153 *
2154 * @param int $userid The id of the user who created the contact request
2155 * @param int $requesteduserid The id of the user confirming the request
2156 */
2157 public static function confirm_contact_request(int $userid, int $requesteduserid) {
2158 global $DB;
2159
2160 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2161 'requesteduserid' => $requesteduserid])) {
2162 self::add_contact($userid, $requesteduserid);
2163
2164 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2165 }
2166 }
2167
2168 /**
2169 * Handles declining a contact request.
2170 *
2171 * @param int $userid The id of the user who created the contact request
2172 * @param int $requesteduserid The id of the user declining the request
2173 */
2174 public static function decline_contact_request(int $userid, int $requesteduserid) {
2175 global $DB;
2176
2177 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
2178 'requesteduserid' => $requesteduserid])) {
2179 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
2180 }
2181 }
2182
2183 /**
2184 * Handles returning the contact requests for a user.
2185 *
2186 * This also includes the user data necessary to display information
2187 * about the user.
2188 *
2189 * It will not include blocked users.
2190 *
2191 * @param int $userid
accd6482
MN
2192 * @param int $limitfrom
2193 * @param int $limitnum
0b3eadcd
MN
2194 * @return array The list of contact requests
2195 */
accd6482 2196 public static function get_contact_requests(int $userid, int $limitfrom = 0, int $limitnum = 0) : array {
0b3eadcd
MN
2197 global $DB;
2198
daa33803
MN
2199 $sql = "SELECT mcr.userid
2200 FROM {message_contact_requests} mcr
0b3eadcd 2201 LEFT JOIN {message_users_blocked} mub
daa33803 2202 ON (mub.userid = ? AND mub.blockeduserid = mcr.userid)
0b3eadcd 2203 WHERE mcr.requesteduserid = ?
0b3eadcd 2204 AND mub.id is NULL
accd6482
MN
2205 ORDER BY mcr.timecreated ASC";
2206 if ($contactrequests = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
daa33803
MN
2207 $userids = array_keys($contactrequests);
2208 return helper::get_member_info($userid, $userids);
2209 }
0b3eadcd 2210
daa33803 2211 return [];
0b3eadcd
MN
2212 }
2213
2214 /**
2215 * Handles adding a contact.
2216 *
2217 * @param int $userid The id of the user who requested to be a contact
2218 * @param int $contactid The id of the contact
2219 */
2220 public static function add_contact(int $userid, int $contactid) {
2221 global $DB;
2222
2223 $messagecontact = new \stdClass();
2224 $messagecontact->userid = $userid;
2225 $messagecontact->contactid = $contactid;
2226 $messagecontact->timecreated = time();
2227 $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
2228
2229 $eventparams = [
2230 'objectid' => $messagecontact->id,
2231 'userid' => $userid,
2232 'relateduserid' => $contactid,
2233 'context' => \context_user::instance($userid)
2234 ];
2235 $event = \core\event\message_contact_added::create($eventparams);
2236 $event->add_record_snapshot('message_contacts', $messagecontact);
2237 $event->trigger();
2238 }
2239
2240 /**
2241 * Handles removing a contact.
2242 *
2243 * @param int $userid The id of the user who is removing a user as a contact
2244 * @param int $contactid The id of the user to be removed as a contact
2245 */
2246 public static function remove_contact(int $userid, int $contactid) {
2247 global $DB;
2248
2249 if ($contact = self::get_contact($userid, $contactid)) {
2250 $DB->delete_records('message_contacts', ['id' => $contact->id]);
2251
2252 $event = \core\event\message_contact_removed::create(array(
2253 'objectid' => $contact->id,
2254 'userid' => $userid,
2255 'relateduserid' => $contactid,
2256 'context' => \context_user::instance($userid)
2257 ));
2258 $event->add_record_snapshot('message_contacts', $contact);
2259 $event->trigger();
2260 }
2261 }
2262
2263 /**
2264 * Handles blocking a user.
2265 *
2266 * @param int $userid The id of the user who is blocking
2267 * @param int $usertoblockid The id of the user being blocked
2268 */
2269 public static function block_user(int $userid, int $usertoblockid) {
2270 global $DB;
2271
2272 $blocked = new \stdClass();
2273 $blocked->userid = $userid;
2274 $blocked->blockeduserid = $usertoblockid;
2275 $blocked->timecreated = time();
2276 $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
2277
2278 // Trigger event for blocking a contact.
2279 $event = \core\event\message_user_blocked::create(array(
2280 'objectid' => $blocked->id,
2281 'userid' => $userid,
2282 'relateduserid' => $usertoblockid,
2283 'context' => \context_user::instance($userid)
2284 ));
2285 $event->add_record_snapshot('message_users_blocked', $blocked);
2286 $event->trigger();
2287 }
2288
2289 /**
2290 * Handles unblocking a user.
2291 *
2292 * @param int $userid The id of the user who is unblocking
2293 * @param int $usertounblockid The id of the user being unblocked
2294 */
2295 public static function unblock_user(int $userid, int $usertounblockid) {
2296 global $DB;
2297
2298 if ($blockeduser = $DB->get_record('message_users_blocked',
2299 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
2300 $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
2301
2302 // Trigger event for unblocking a contact.
2303 $event = \core\event\message_user_unblocked::create(array(
2304 'objectid' => $blockeduser->id,
2305 'userid' => $userid,
2306 'relateduserid' => $usertounblockid,
2307 'context' => \context_user::instance($userid)
2308 ));
2309 $event->add_record_snapshot('message_users_blocked', $blockeduser);
2310 $event->trigger();
2311 }
2312 }
2313
2314 /**
2315 * Checks if users are already contacts.
2316 *
2317 * @param int $userid The id of one of the users
2318 * @param int $contactid The id of the other user
2319 * @return bool Returns true if they are a contact, false otherwise
2320 */
2321 public static function is_contact(int $userid, int $contactid) : bool {
2322 global $DB;
2323
2324 $sql = "SELECT id
2325 FROM {message_contacts} mc
2326 WHERE (mc.userid = ? AND mc.contactid = ?)
2327 OR (mc.userid = ? AND mc.contactid = ?)";
2328 return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
2329 }
2330
2331 /**
2332 * Returns the row in the database table message_contacts that represents the contact between two people.
2333 *
2334 * @param int $userid The id of one of the users
2335 * @param int $contactid The id of the other user
2336 * @return mixed A fieldset object containing the record, false otherwise
2337 */
2338 public static function get_contact(int $userid, int $contactid) {
2339 global $DB;
2340
2341 $sql = "SELECT mc.*
2342 FROM {message_contacts} mc
2343 WHERE (mc.userid = ? AND mc.contactid = ?)
2344 OR (mc.userid = ? AND mc.contactid = ?)";
2345 return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
2346 }
2347
2348 /**
2349 * Checks if a user is already blocked.
2350 *
0b3eadcd
MN
2351 * @param int $userid
2352 * @param int $blockeduserid
2353 * @return bool Returns true if they are a blocked, false otherwise
2354 */
2355 public static function is_blocked(int $userid, int $blockeduserid) : bool {
2356 global $DB;
2357
2358 return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
2359 }
2360
2361 /**
2362 * Checks if a contact request already exists between users.
2363 *
2364 * @param int $userid The id of the user who is creating the contact request
2365 * @param int $requesteduserid The id of the user being requested
2366 * @return bool Returns true if a contact request exists, false otherwise
2367 */
2368 public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
2369 global $DB;
2370
2371 $sql = "SELECT id
2372 FROM {message_contact_requests} mcr
2373 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
2374 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
2375 return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
2376 }
08cb8a34
MN
2377
2378 /**
2379 * Checks if a user is already in a conversation.
2380 *
2381 * @param int $userid The id of the user we want to check if they are in a group
2382 * @param int $conversationid The id of the conversation
2383 * @return bool Returns true if a contact request exists, false otherwise
2384 */
2385 public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
2386 global $DB;
2387
2388 return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
2389 'userid' => $userid]);
7983fb83
SA
2390 }
2391
2392 /**
2393 * Checks if the sender can message the recipient.
2394 *
9f82758c
JD
2395 * @param int $recipientid
2396 * @param int $senderid
7983fb83
SA
2397 * @return bool true if recipient hasn't blocked sender and sender can contact to recipient, false otherwise.
2398 */
9f82758c
JD
2399 protected static function can_contact_user(int $recipientid, int $senderid) : bool {
2400 if (has_capability('moodle/site:messageanyuser', \context_system::instance(), $senderid)) {
7983fb83
SA
2401 // The sender has the ability to contact any user across the entire site.
2402 return true;
2403 }
2404
2405 // The initial value of $cancontact is null to indicate that a value has not been determined.
2406 $cancontact = null;
2407
9f82758c 2408 if (self::is_blocked($recipientid, $senderid)) {
7983fb83
SA
2409 // The recipient has specifically blocked this sender.
2410 $cancontact = false;
2411 }
2412
2413 $sharedcourses = null;
2414 if (null === $cancontact) {
2415 // There are three user preference options:
2416 // - Site: Allow anyone not explicitly blocked to contact me;
2417 // - Course members: Allow anyone I am in a course with to contact me; and
2418 // - Contacts: Only allow my contacts to contact me.
2419 //
2420 // The Site option is only possible when the messagingallusers site setting is also enabled.
2421
9f82758c 2422 $privacypreference = self::get_user_privacy_messaging_preference($recipientid);
7983fb83
SA
2423 if (self::MESSAGE_PRIVACY_SITE === $privacypreference) {
2424 // The user preference is to allow any user to contact them.
2425 // No need to check anything else.
2426 $cancontact = true;
2427 } else {
2428 // This user only allows their own contacts, and possibly course peers, to contact them.
2429 // If the users are contacts then we can avoid the more expensive shared courses check.
9f82758c 2430 $cancontact = self::is_contact($senderid, $recipientid);
7983fb83
SA
2431
2432 if (!$cancontact && self::MESSAGE_PRIVACY_COURSEMEMBER === $privacypreference) {
2433 // The users are not contacts and the user allows course member messaging.
2434 // Check whether these two users share any course together.
9f82758c 2435 $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
7983fb83
SA
2436 $cancontact = (!empty($sharedcourses));
2437 }
2438 }
2439 }
2440
2441 if (false === $cancontact) {
2442 // At the moment the users cannot contact one another.
2443 // Check whether the messageanyuser capability applies in any of the shared courses.
2444 // This is intended to allow teachers to message students regardless of message settings.
2445
2446 // Note: You cannot use empty($sharedcourses) here because this may be an empty array.
2447 if (null === $sharedcourses) {
9f82758c 2448 $sharedcourses = enrol_get_shared_courses($recipientid, $senderid, true);
7983fb83
SA
2449 }
2450
2451 foreach ($sharedcourses as $course) {
2452 // Note: enrol_get_shared_courses will preload any shared context.
9f82758c 2453 if (has_capability('moodle/site:messageanyuser', \context_course::instance($course->id), $senderid)) {
7983fb83
SA
2454 $cancontact = true;
2455 break;
2456 }
2457 }
2458 }
08cb8a34 2459
7983fb83 2460 return $cancontact;
08cb8a34 2461 }
67b81351 2462
623048af
AA
2463 /**
2464 * Add some new members to an existing conversation.
2465 *
2466 * @param array $userids User ids array to add as members.
2467 * @param int $convid The conversation id. Must exists.
2468 * @throws \dml_missing_record_exception If convid conversation doesn't exist
2469 * @throws \dml_exception If there is a database error
83e3a4fe 2470 * @throws \moodle_exception If trying to add a member(s) to a non-group conversation
623048af
AA
2471 */
2472 public static function add_members_to_conversation(array $userids, int $convid) {
2473 global $DB;
2474
2475 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2476
83e3a4fe
MN
2477 // We can only add members to a group conversation.
2478 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2479 throw new \moodle_exception('You can not add members to a non-group conversation.');
2480 }
2481
623048af
AA
2482 // Be sure we are not trying to add a non existing user to the conversation. Work only with existing users.
2483 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
4abe3d25 2484 $existingusers = $DB->get_fieldset_select('user', 'id', "id $useridcondition", $params);
623048af
AA
2485
2486 // Be sure we are not adding a user is already member of the conversation. Take all the members.
2487 $memberuserids = array_values($DB->get_records_menu(
2488 'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
2489 );
2490
2491 // Work with existing new members.
2492 $members = array();
2493 $newuserids = array_diff($existingusers, $memberuserids);
2494 foreach ($newuserids as $userid) {
2495 $member = new \stdClass();
2496 $member->conversationid = $convid;
2497 $member->userid = $userid;
2498 $member->timecreated = time();
2499 $members[] = $member;
2500 }
2501
623048af 2502 $DB->insert_records('message_conversation_members', $members);
623048af
AA
2503 }
2504
2505 /**
2506 * Remove some members from an existing conversation.
2507 *
2508 * @param array $userids The user ids to remove from conversation members.
2509 * @param int $convid The conversation id. Must exists.
2510 * @throws \dml_exception
83e3a4fe 2511 * @throws \moodle_exception If trying to remove a member(s) from a non-group conversation
623048af
AA
2512 */
2513 public static function remove_members_from_conversation(array $userids, int $convid) {
2514 global $DB;
2515
2516 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
2517
83e3a4fe
MN
2518 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
2519 throw new \moodle_exception('You can not remove members from a non-group conversation.');
2520 }
2521
623048af
AA
2522 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
2523 $params['convid'] = $convid;
2524
623048af
AA
2525 $DB->delete_records_select('message_conversation_members',
2526 "conversationid = :convid AND userid $useridcondition", $params);
623048af
AA
2527 }
2528
2529 /**
2530 * Count conversation members.
2531 *
2532 * @param int $convid The conversation id.
2533 * @return int Number of conversation members.
2534 * @throws \dml_exception
2535 */
2536 public static function count_conversation_members(int $convid) : int {
2537 global $DB;
08cb8a34 2538
623048af 2539 return $DB->count_records('message_conversation_members', ['conversationid' => $convid]);
08cb8a34 2540 }
55fda006 2541
f0e137c5
MN
2542 /**
2543 * Checks whether or not a conversation area is enabled.
2544 *
2545 * @param string $component Defines the Moodle component which the area was added to.
2546 * @param string $itemtype Defines the type of the component.
2547 * @param int $itemid The id of the component.
2548 * @param int $contextid The id of the context.
2549 * @return bool Returns if a conversation area exists and is enabled, false otherwise
2550 */
2551 public static function is_conversation_area_enabled(string $component, string $itemtype, int $itemid, int $contextid) : bool {
2552 global $DB;
2553
76540bec 2554 return $DB->record_exists('message_conversations',
f0e137c5
MN
2555 [
2556 'itemid' => $itemid,
2557 'contextid' => $contextid,
2558 'component' => $component,
2559 'itemtype' => $itemtype,
76540bec 2560 'enabled' => self::MESSAGE_CONVERSATION_ENABLED
f0e137c5
MN
2561 ]
2562 );
2563 }
2564
e7f46714 2565 /**
76540bec 2566 * Get conversation by area.
e7f46714 2567 *
2568 * @param string $component Defines the Moodle component which the area was added to.
2569 * @param string $itemtype Defines the type of the component.
76540bec
MN
2570 * @param int $itemid The id of the component.
2571 * @param int $contextid The id of the context.
2572 * @return \stdClass
e7f46714 2573 */
76540bec 2574 public static function get_conversation_by_area(string $component, string $itemtype, int $itemid, int $contextid) {
e7f46714 2575 global $DB;
2576
76540bec 2577 return $DB->get_record('message_conversations',
f0e137c5
MN
2578 [
2579 'itemid' => $itemid,
2580 'contextid' => $contextid,
2581 'component' => $component,
2582 'itemtype' => $itemtype
2583 ]
2584 );
e7f46714 2585 }
2586
2587 /**
76540bec 2588 * Enable a conversation.
e7f46714 2589 *
76540bec 2590 * @param int $conversationid The id of the conversation.
e7f46714 2591 * @return void
2592 */
76540bec 2593 public static function enable_conversation(int $conversationid) {
e7f46714 2594 global $DB;
2595
76540bec
MN
2596 $conversation = new \stdClass();
2597 $conversation->id = $conversationid;
2598 $conversation->enabled = self::MESSAGE_CONVERSATION_ENABLED;
2599 $conversation->timemodified = time();
2600 $DB->update_record('message_conversations', $conversation);
e7f46714 2601 }
2602
2603 /**
76540bec 2604 * Disable a conversation.
e7f46714 2605 *
76540bec 2606 * @param int $conversationid The id of the conversation.
e7f46714 2607 * @return void
2608 */
76540bec 2609 public static function disable_conversation(int $conversationid) {
e7f46714 2610 global $DB;
2611
76540bec
MN
2612 $conversation = new \stdClass();
2613 $conversation->id = $conversationid;
2614 $conversation->enabled = self::MESSAGE_CONVERSATION_DISABLED;
2615 $conversation->timemodified = time();
2616 $DB->update_record('message_conversations', $conversation);
e7f46714 2617 }
2618
2619 /**
2620 * Update the name of a conversation.
2621 *
76540bec 2622 * @param int $conversationid The id of a conversation.
e7f46714 2623 * @param string $name The main name of the area
2624 * @return void
2625 */
2626 public static function update_conversation_name(int $conversationid, string $name) {
2627 global $DB;
2628
2629 if ($conversation = $DB->get_record('message_conversations', array('id' => $conversationid))) {
2630 if ($name <> $conversation->name) {
2631 $conversation->name = $name;
f0e137c5 2632 $conversation->timemodified = time();
e7f46714 2633 $DB->update_record('message_conversations', $conversation);
2634 }
2635 }
2636 }
6ecd6e5b
MN
2637
2638 /**
2639 * Returns a list of conversation members.
2640 *
2641 * @param int $userid The user we are returning the conversation members for, used by helper::get_member_info.
2642 * @param int $conversationid The id of the conversation
2643 * @param bool $includecontactrequests Do we want to include contact requests with this data?
2644 * @param int $limitfrom
2645 * @param int $limitnum
2646 * @return array
2647 */
2648 public static function get_conversation_members(int $userid, int $conversationid, bool $includecontactrequests = false,
2649 int $limitfrom = 0, int $limitnum = 0) : array {
2650 global $DB;
2651
2652 if ($members = $DB->get_records('message_conversation_members', ['conversationid' => $conversationid],
2653 'timecreated ASC, id ASC', 'userid', $limitfrom, $limitnum)) {
2654 $userids = array_keys($members);
054834b0 2655 $members = helper::get_member_info($userid, $userids, $includecontactrequests);
6ecd6e5b
MN
2656
2657 return $members;
2658 }
2659
2660 return [];
2661 }
879e2bef 2662}