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